Home >Backend Development >PHP Tutorial >How Can I Efficiently Iterate Through Two Arrays Simultaneously in PHP?

How Can I Efficiently Iterate Through Two Arrays Simultaneously in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-04 03:01:11992browse

How Can I Efficiently Iterate Through Two Arrays Simultaneously in PHP?

How can I loop through two arrays at once? [duplicate]

Problem


The problem lies in your nested foreach loop, which iterates over the entire $data2 array for each element of the $data1 array. This results in a total of $data1 * $data2 iterations.

Solutions


array_map() method (PHP >=5.3)

array_map(function($v1, $v2){
    echo $v1 . "<br>";
    echo $v2 . "<strong><br><br></strong>";
}, $data1, $data2 /* , Add more arrays if needed manually */);

MultipleIterator method (PHP >=5.3)

$it = new MultipleIterator();
$it->attachIterator(new ArrayIterator($data1));
$it->attachIterator(new ArrayIterator($data2));
//Add more arrays if needed

foreach($it as $a) {
    echo $a[0] . "<br>";
    echo $a[1] . "<strong><br><br></strong>";
}

for loop method (PHP >=4.3)

$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]] . "<strong><br><br></strong>";
}

array_combine() method (PHP >=5.0)

foreach(array_combine($data1, $data2) as $d1 => $d2) {
    echo $d1 . "<br>";
    echo $d2 . "<strong><br><br></strong>";
}

call_user_func_array() method (PHP >=5.6)

$func = function(...$numbers){
    foreach($numbers as $v)
        echo $v . "<br>";
    echo "<strong><br></strong>";
};
call_user_func_array("array_map", [$func, $data1, $data2]);

The above is the detailed content of How Can I Efficiently Iterate Through Two Arrays Simultaneously in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn