5

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.

Jonathan Leffler
760k145 gold badges962 silver badges1.3k bronze badges
asked Feb 23, 2010 at 23:11

3 Answers 3

35
$array = explode(',', $variable);
answered Feb 23, 2010 at 23:12
Sign up to request clarification or add additional context in comments.

Comments

5

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"
}
answered Feb 23, 2010 at 23:55

Comments

1

you can also use preg_split()

$variable = 'left , middle, right';
print_r ( preg_split("/\s*,\s*/",$variable));
answered Feb 24, 2010 at 0:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.