Home >Backend Development >PHP Tutorial >How to Efficiently Iterate Through Two Arrays Simultaneously in PHP?
To simultaneously loop through two arrays, the code provided in the question employs nested foreach loops. However, this approach is inefficient as it produces incorrect results.
Here are effective solutions to overcome this challenge:
This method allows simultaneous looping through multiple arrays.
array_map(function($v1, $v2){ echo $v1 . "<br>"; echo $v2 . "<br><br>"; }, $data1, $data2);
Create a MultipleIterator and attach ArrayIterators for the desired arrays.
$it = new MultipleIterator(); $it->attachIterator(new ArrayIterator($data1)); $it->attachIterator(new ArrayIterator($data2)); foreach($it as $a) { echo $a[0] . "<br>"; echo $a[1] . "<br><br>"; }
Use a for loop with a counter to access corresponding elements from both arrays.
$keysOne = array_keys($data1); $keysTwo = array_keys($data2); $min = min(count($data1), count($data2)); for($i = 0; $i < $min; $i++) { echo $data1[$keysOne[$i]] . "<br>"; echo $data2[$keysTwo[$i]] . "<br><br>"; }
If the arrays have unique values, use array_combine() to create a single array with the elements from the first array as keys and those from the second array as values.
foreach(array_combine($data1, $data2) as $d1 => $d2) { echo $d1 . "<br>"; echo $d2 . "<br><br>"; }
To loop through an unknown number of arrays, combine array_map() with call_user_func_array().
$func = function(...$numbers){ foreach($numbers as $v) echo $v . "<br>"; echo "<br>"; }; call_user_func_array("array_map", [$func, $data1, $data2]);
The above is the detailed content of How to Efficiently Iterate Through Two Arrays Simultaneously in PHP?. For more information, please follow other related articles on the PHP Chinese website!