Comma string to array

I am looking for the simplest way to take a single variable, for example:

$variable = 'left,middle,right';

and write it into a split array();in commas.

+5
source share
3 answers
$array = explode(',', $variable);
+29
source

If the string is a little more complicated (i.e. the elements may be in quotation marks, and both the delimiter and the quotation mark symbol may appear inside the element), you may also be interested in fgetcsv () and str_getcsv ()

$variable = '"left,right","middle", "up,down"';
$row = str_getcsv($variable);
var_dump($row);

prints

array(3) {
  [0]=>
  string(10) "left,right"
  [1]=>
  string(6) "middle"
  [2]=>
  string(7) "up,down"
}
+4
source

you can also use preg_split()

$variable = 'left  ,  middle,   right';
print_r ( preg_split("/\s*,\s*/",$variable));
+1
source

All Articles