str_getcsv() Function in PHP 8.2 With Example

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

Hello Friends Today, through this tutorial, I will tell you How to Use `str_getcsv()` function using PHP, PHP 8, PHP 8.1, PHP 8.2 With Example. In PHP, the `str_getcsv()` function is used to parse a CSV string into an array. It takes a CSV-formatted string as input and returns an array containing the fields parsed from the CSV data. This function is particularly useful when you have CSV data stored in a string variable rather than in a file.

Here’s an example demonstrating the usage of `str_getcsv()` in PHP 8.2:


// CSV string to parse
$csvString = "John,Doe,30\nJane,Smith,25\n";

// Parsing CSV string using str_getcsv()
$rows = str_getcsv($csvString, "\n"); // Splitting CSV by lines
$csvData = array();

// Loop through each row and parse fields
foreach ($rows as $row) {
$csvData[] = str_getcsv($row, ","); // Splitting each row by commas

// Output the parsed CSV data


In this example:

1. We have a CSV string containing two rows with three fields each: name, surname, and age, separated by commas.
2. We use `str_getcsv()` twice: first to split the CSV string into rows using newline (`\n`) as the delimiter, and then to split each row into individual fields using a comma (`,`) as the delimiter.
3. The parsed CSV data is stored in the `$csvData` array.
4. Finally, we use `print_r()` to output the parsed CSV data for demonstration purposes.

When you run this script, it will output:

[0] => Array
[0] => John
[1] => Doe
[2] => 30
[1] => Array
[0] => Jane
[1] => Smith
[2] => 25

Each element of the `$csvData` array corresponds to a row in the CSV data, and each row is represented as an array containing individual fields.