0

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.

3 Answers 3

2

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 />';
}
Sign up to request clarification or add additional context in comments.

Comments

1

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]);
}

2 Comments

ok I see what you mean but the number in my list isn't actually necessarily in order, maybe I will edit my question
It doesn't matter if numbers in your list are in order or not, the above loop will still work.
0

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:

foreach($options as $key=>$value){
   print("$key: $value\n");
}

Comments

Your Answer

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.