Take the 2-minute tour ×

Ok so tbh the title isn't very good I just don't know how to explain what i'm trying to do in 1 short sentence so I will do my best here....

I have an array

$options = array('156656', 'bar', '235456','soft', '353636','eve', '4356563', 'evil');

I want number and name to be partnered/linked so have done this by splitting with list() ...

list($number, $name) = $options; 

echo $name . ' : ' . $number . '<br />';

which shows as

 156656 : bar

but what I need is for all to be listed like so ...

156656 : bar
235456 : soft
353636 : eve
4356563 : evil

I'm guessing this is done with a foreach but what ever I try fails

As always all help is appreciated and thanks in advance.

share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

You can use array_chunk to get sub arrays like below:

$options = array('1', 'bar', '2','soft', '3','eve', '4', 'evil');
foreach (array_chunk($options, 2) as $sub) {
     list($number, $name) = $sub; 
     echo $number . ' : ' . $name . '<br />';
share|improve this answer
Thank you xdazz –  Dizzi Oct 29 '11 at 5:24
add comment

How about enumerating two at a time:

for ($i = 0; 2 * $i < count($arr); ++$i)
  print("First: " . $arr[2 * $i] . ", Second: " $arr[2 * $i + 1]);
share|improve this answer
ok I see what you mean but the number in my list isn't actually necessarily in order, maybe I will edit my question –  Dizzi Oct 29 '11 at 5:18
It doesn't matter if numbers in your list are in order or not, the above loop will still work. –  guru Oct 29 '11 at 5:21
add comment

Try using associative arrays, for this application, as well:

$options = array('156656'=>'bar', '235456'=>'soft', '353636'=>'eve', '4356563'=>'evil');

Then, you can use foreach on it as so:

   print("$key: $value\n");
share|improve this answer
add comment

Your Answer


