If I have a string $myString = "apple, banana, cherry"
and I want to get this data into an array, then I have two options.
$myArray = explode(", ", $myString)
or
$myArray = str_getcsv($myString)
both give the same result.
Can anybody explain the advantage/disadvantage of using one of these methods over the other?
I've heard that str_getcsv is better, according to the php manual "because explode() would not treat possible enclosured parts of string or escaped characters correctly."
Can anybody please explain what this means with the aid of a simple example?
Thanks
str_getcsv
works on CSV such as:
"column 1", "column 2", and the third part
123, 567, 89
It unwraps all quoted parts, and strips the spaces from either end.
Now your simplistic explode would also do the space trimming. But it would fail / be less reliable if there is some variance in it:
1,2,3, 4, 5, 6, 7
If you are certain that there's always one comma and one space after each bit, then explode(", "
would suffice. But str_getcsv is a bit more clever. It also allows to have the delimiter in quotes, as the manual hint alludes to:
"column 1 contains a , comma", "col 2 starts here"
Where the simple explode would be unaware of the special treatment for the contained comma and space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With