349

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,admin@example.com,8

Output:

['9', 'admin@example', '8']  
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Kevin
  • 23,174
  • 26
  • 81
  • 111
  • Also see [how to split by more than one character](https://stackoverflow.com/a/3679042/8740349), like `preg_split('/[-,\s]+/', 'Split-this, by dash comma and space');` for example – Top-Master Jul 03 '21 at 07:00

9 Answers9

715

Try explode:

$myString = "9,admin@example.com,8";
$myArray = explode(',', $myString);
print_r($myArray);

Output :

Array
(
    [0] => 9
    [1] => admin@example.com
    [2] => 8
)
Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
Matthew Groves
  • 25,181
  • 9
  • 71
  • 121
  • 1
    How you can get count ? .lengh? –  Nov 11 '15 at 09:24
  • 2
    One way is to use count() (aka sizeof) - http://php.net/manual/en/function.count.php – Matthew Groves Nov 11 '15 at 13:19
  • 3
    @McLosysCreative You might also like `var_dump` which gives more detailed information. Even more usefull is `var_export($myArray, true)` because it returns the output of `var_dump` as a string so you can store it in some log without breaking generated site... – Tomasz Kapłoński Apr 20 '16 at 11:13
45
$string = '9,admin@google.com,8';
$array = explode(',', $string);

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

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
32

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.

soulmerge
  • 73,842
  • 19
  • 118
  • 155
8

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
)
chx
  • 11,270
  • 7
  • 55
  • 129
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 : []));
}
oriadam
  • 7,747
  • 2
  • 50
  • 48
  • much prefered this answer, since preg_split is much more foolproof, when it contains user inputs. – Stender Oct 21 '20 at 14:03
  • This answer is going to be far less efficient than using `explode()`. I would not put this in any professional script. If it is possible for your incoming string to be empty, then write a simple falsey check before exploding instead of using a `preg_` call containing a literal character. If a string might have a trailing delimiter and you don't want that, then just `rtrim()` the delimiter off -- again, no reason to lean on regex (and I love regex). – mickmackusa Mar 10 '21 at 12:12
  • Posted many years earlier: https://stackoverflow.com/a/64608/2943403 – mickmackusa Mar 10 '21 at 12:27
4

Use explode() or preg_split() function to split the string in php with given delimiter

// Use preg_split() function 
$string = "123,456,78,000";  
$str_arr = preg_split ("/\,/", $string);  
print_r($str_arr); 
  
// use of explode 
$string = "123,46,78,000"; 
$str_arr = explode (",", $string);  
print_r($str_arr); 
fajr abd el ali
  • 137
  • 1
  • 3
  • 1
    A comma does not have special meaning in regex, so there is no need to escape it -- this is only going to teach unnecessary coding practices. `preg_split()` with a literal character is an inappropriate usage of regex and will only mean needless processing overhead. I would not recommend the first technique to any researcher. As for the `explode()` this insight was already offered years earlier. This answer can be safely deleted. – mickmackusa Mar 10 '21 at 12:16
1

If anyone wants to convert comma seprated string into a list item using for-each then it will help you ... This code is for blade template

@php
$data = $post->tags;
$sep_tag= explode(',', $data);
@endphp

@foreach ($sep_tag as $tag)
 <li class="collection-item">{{ $tag}}</li>
 @endforeach 
Akash Pise
  • 90
  • 2
  • 13
0
//Re-usable function
function stringToArray($stringSeperatedCommas)
{
    return collect(explode(',', $stringSeperatedCommas))->map(function ($string) {
        return trim($string) != null ? trim($string) : null;
    })->filter(function ($string) {
        return trim($string) != null;
    });
}

//Usage
$array = stringToArray('abcd, , dsdsd, dsds');
print($array);

//Result
{ "abcd", "dsdsd", "dsds" }
Akash Kumar
  • 129
  • 2
  • 6
0

There may be spaces between commas. Also there may be no useful data between commas. Function preg_split will help to handle these cases:

$str = "1,2 ,  ,4, ";

$arr = preg_split("/\s*,\s*/", $str, -1, PREG_SPLIT_NO_EMPTY);

print_r($arr); // [1, 2, 4]
yesnik
  • 4,085
  • 2
  • 30
  • 25