1

I have a field in my DB that holds value separated by commas like;

$tmp_list = "COB,ISJ,NSJ,"

Now when I fetch that the row, I would like to have them in an array. I have used array($tmp_list) but I get the values in one line only like:

[0] => 'COB,ISJ,NSJ,'

instead of

[0] => 'COB',
[1] => 'ISJ',
[2] => 'NSJ'

All help is appriciated.

1 Answer 1

4

Use explode:

$arr = explode(',', $tmp_list);

If you like, remove the trailing comma using rtrim first:

$arr = explode(',', rtrim($tmp_list, ','));

You can also trim each element if there's a chance of getting any unwanted leading/trailing whitespace in one or more elements (as per @machine's suggestion):

$arr = array_map('trim', explode(',', rtrim($tmp_list, ',')));
Sign up to request clarification or add additional context in comments.

1 Comment

you might also want to run all elements through the trim-function, in case it's saved with spaces in the database: array_map( 'trim', explode( ',', $tmp_list ) );

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.