4

Possible Duplicate:
Multiple index variables in PHP foreach loop

Can we echo multiple arrays using single foreach statement?

Tried doing it in following way but wasn't successful:

foreach($cars, $ages as $value1, $value2)
{
    echo $value1.$value2;
}
4
  • That would be nice to be able to do, but I think you're going to need to use indexes. Are the arrays always the same length? Commented Nov 13, 2011 at 8:26
  • @Yzmir arrays are of different lenght. Commented Nov 13, 2011 at 8:30
  • 6
    If they are different lengths, this doesn't really make sense to do anyway. Commented Nov 13, 2011 at 8:31
  • 1
    You have to be very careful with trying to foreach over two arrays here. For instance, what happens when you try to sort the $cars array by car brand? In that case, the $ages array becomes useless. I think the best way to go, is to have a single array filled with some sort of CarAge objects and foreach over that array. Commented Nov 13, 2011 at 8:34

1 Answer 1

11

assuming both arrays have the same amount of elements, this should work

foreach(array_combine($cars, $ages) as $car => $age){
    echo $car.$age;
}

if the arrays are not guaranteed to be the same length then you can do something like this

$len = max(count($ages), count($cars));
for($i=0; $i<$len; $i++){
    $car = isset($cars[$i]) ? $cars[$i] : '';
    $age = isset($ages[$i]) ? $ages[$i] : '';
    echo $car.$age;
}

if you just want to join the two arrays, you can do it like this

foreach(array_merge($cars, $ages) as $key => $value){
    echo $key . $value;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Wow you beat me. Also your code is exactly the same as mine :D -- +1
Using array_combine() won't work because the arrays are not the same size according to the person asking the question. array_combine() will return FALSE when the arrays are not the same size. Perhaps you could pad the smaller array?
I like your edit to handle different length arrays better than my Answer. +1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.