Split a comma-delimited string into an array?

508,338

Solution 1

Try explode:

$myString = "9,[email protected],8";
$myArray = explode(',', $myString);
print_r($myArray);

Output :

Array
(
    [0] => 9
    [1] => [email protected]
    [2] => 8
)

Solution 2

$string = '9,[email protected],8';
$array = explode(',', $string);

For more complicated situations, you may need to use preg_split.

Solution 3

If that string comes from a csv file, I would use fgetcsv() (or str_getcsv() if you have PHP V5.3). That will allow you to parse quoted values correctly. If it is not a csv, explode() should be the best choice.

Solution 4

What if you want your parts to contain commas? Well, quote them. And then what about the quotes? Well, double them up. In other words:

part1,"part2,with a comma and a quote "" in it",part3

PHP provides the https://php.net/str_getcsv function to parse a string as if it were a line in a CSV file which can be used with the above line instead of explode:

print_r(str_getcsv('part1,"part2,with a comma and a quote "" in it",part3'));
Array
(
    [0] => part1
    [1] => part2,with a comma and a quote " in it
    [2] => part3
)

Solution 5

explode has some very big problems in real life usage:

count(explode(',', null)); // 1 !! 
explode(',', null); // [""] not an empty array, but an array with one empty string!
explode(',', ""); // [""]
explode(',', "1,"); // ["1",""] ending commas are also unsupported, kinda like IE8

this is why i prefer preg_split

preg_split('@,@', $string, NULL, PREG_SPLIT_NO_EMPTY)

the entire boilerplate:

/** @brief wrapper for explode
 * @param string|int|array $val string will explode. '' return []. int return string in array (1 returns ['1']). array return itself. for other types - see $as_is
 * @param bool $as_is false (default): bool/null return []. true: bool/null return itself.
 * @param string $delimiter default ','
 * @return array|mixed
 */
public static function explode($val, $as_is = false, $delimiter = ',')
{
    // using preg_split (instead of explode) because it is the best way to handle ending comma and avoid empty string converted to ['']
    return (is_string($val) || is_int($val)) ?
        preg_split('@' . preg_quote($delimiter, '@') . '@', $val, NULL, PREG_SPLIT_NO_EMPTY)
        :
        ($as_is ? $val : (is_array($val) ? $val : []));
}
Share:
508,338
Kevin
Author by

Kevin

Updated on August 17, 2021

Comments

  • Kevin
    Kevin over 2 years

    I need to split my string input into an array at the commas.

    Is there a way to explode a comma-separated string into a flat, indexed array?

    Input:

    9,[email protected],8
    

    Output:

    ['9', 'admin@example', '8']