Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple array echo with foreach statement in php [duplicate]

Tags:

arrays

php

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;
}
like image 281
user1043972 Avatar asked Dec 21 '22 06:12

user1043972


1 Answers

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;
}
like image 131
Ilia Choly Avatar answered Dec 24 '22 00:12

Ilia Choly