Take the 2-minute tour ×

I have the following values:

$attached_products = "1,4,3";

I want to make an array that looks like:

$selected = array(1, 4, 3);

using a loop with my $attached_products.

share|improve this question
add comment

3 Answers

up vote 7 down vote accepted

This could be done with a loop, but there's a simpler way.

You can break your string up around the commas using the explode function[php docs]. This will give you an array of strings of digits. You can convert each string to an integer by applying intval[php docs] using array_map[php docs].

$attached_products = "1,4,3";
$selected_strings = explode(',', $attached_products); # == array('1', '4', '3')
$selected = array_map('intval', $selected_strings);   # == array(1, 4, 3)
share|improve this answer
thanks for your response @Jeremy Banks, hmmm is that output equal to array(1, 4, 3)? –  Emkey Sep 14 '11 at 1:48
intval needs to be quoted. –  alex Sep 14 '11 at 1:50
@Emkey: My values were strings, not integers. I've fixed that. Now they are the same. –  Jeremy Banks Sep 14 '11 at 1:54
@alex: thanks, fixed. –  Jeremy Banks Sep 14 '11 at 1:55
Wow that's working thanks a lot! :) –  Emkey Sep 14 '11 at 1:58
add comment

You use explode() for that:

$selected = explode(", ", $attached_products);
share|improve this answer
add comment

If there may or may not be whitespace after the comma, you could use preg_split().

$selected = preg_split(/,\s*/, $attached_products);

Alternatively you could use explode(), trim() and array_map().

$selected = array_map('trim', explode(',', $attached_products));

If they must be integers, map them through intval().

share|improve this answer
add comment

Your Answer


