tags:

views:

29

answers:

1

Hello,

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.

+4  A: 

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, ',')));
karim79
Thank you karim79
Adnan
You have to right trim it before.
Artefacto
@Artefacto, already edited in while you commented, I guess.
karim79
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 ) );
PatrikAkerstrand
@Machine - +1, good suggestion and duly edited. Thank you.
karim79