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;
}
Community
  • 1
  • 1
user1043972
  • 43
  • 1
  • 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? – Yzmir Ramirez Nov 13 '11 at 08:26
  • @Yzmir arrays are of different lenght. – user1043972 Nov 13 '11 at 08:30
  • 6
    If they are different lengths, this doesn't really make sense to do anyway. – Mike Lentini Nov 13 '11 at 08: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. – Roy Nov 13 '11 at 08:34

1 Answers1

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;
}
Ilia Choly
  • 18,070
  • 14
  • 92
  • 160
  • 1
    Wow you beat me. Also your code is exactly the same as mine :D -- +1 – fardjad Nov 13 '11 at 08:31
  • 2
    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? – Yzmir Ramirez Nov 13 '11 at 08:35
  • I like your edit to handle different length arrays better than my Answer. +1 – Yzmir Ramirez Nov 13 '11 at 08:56