Multiple array echo with foreach statement in php

Possible duplicate:
Multiple index variables in PHP foreach loop

Can we echo multiple arrays using a single foreach ?

I tried to do this as follows, but was not successful:

 foreach($cars, $ages as $value1, $value2) { echo $value1.$value2; } 
+4
source share
1 answer

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

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

if arrays are not guaranteed the same length, 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 two arrays you can do it like this

 foreach(array_merge($cars, $ages) as $key => $value){ echo $key . $value; } 
+10
source

Source: https://habr.com/ru/post/1380982/


All Articles