Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comma-separated string to array

Tags:

php

I'm looking for the simplest way to take a single variable such as:

$variable = 'left,middle,right';

and write it to an array(); split at the commas.

like image 516
CLiown Avatar asked Feb 23 '10 23:02

CLiown


2 Answers

$array = explode(',', $variable);
like image 65
jasonbar Avatar answered Sep 30 '22 07:09

jasonbar


In case you string gets a little bit more complex (i.e. elements can be in quotes and both the delimiter and the quoting character can appear within an element) you might 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"
}
like image 32
VolkerK Avatar answered Sep 30 '22 07:09

VolkerK