In this tutorial, you shall learn how to parse a given string into an array in PHP using str_getcsv() function, with example programs.
PHP – Parse CSV String into Array
To parse a CSV string into an array in PHP, call str_getcsv()
String function and pass the CSV string as argument.
str_getcsv()
String function takes string as an argument, and parses the given string for fields in CSV format and returns an array.
Examples
1. Parse CSV string into array
In the following example, we take a CSV String and parse it into an array using str_getcsv()
function.
PHP Program
<?php
$input = 'apple,banana,cherry';
$output = str_getcsv($input);
foreach ($output as $x) {
echo $x;
echo '<br>';
}
?>
Output
2. Parse comma separated numbers in string into array
In the following example, we take a CSV String which contains some numbers separated by comma, and parse it into an array using str_getcsv()
function.
The resulting array is still a string array, we may need to convert it to numeric array if required.
PHP Program
<?php
$input = '2,4,6,8,10,12';
$output = str_getcsv($input);
foreach ($output as $x) {
echo $x;
echo '<br>';
}
?>
Output
Conclusion
In this PHP Tutorial, we learned how to convert CSV string into an Array, using str_getcsv()
function, with examples.