Iterating multiple arrays together

suggest change

Sometimes two arrays of the same length need to be iterated together, for example:

$people = ['Tim', 'Tony', 'Turanga'];
$foods = ['chicken', 'beef', 'slurm'];

array_map is the simplest way to accomplish this:

echo implode(array_map(function($person, $food) {
    return "$person likes $food\n";
}, $people, $foods));

array_map returns the lines. echo implode(...) prints them:

Tim likes chicken
Tony likes beef
Turanga likes slurm

This can be done through a common index:

assert(count($people) === count($foods));
for ($i = 0; $i < count($people); $i++) {
    echo "$people[$i] likes $foods[$i]\n";
}

If the two arrays don’t have the incremental keys, array_values($array)[$i] can be used to replace $array[$i].

If both arrays have the same order of keys, you can also use a foreach-with-key loop on one of the arrays:

foreach ($people as $index => $person) {
    $food = $foods[$index];
    echo "$person likes $food\n";
}

That foreach works when both arrays use the same keys. A for loop over array_values does not need the original keys to match. Different lengths make $foods[$index] undefined.

You can also use array_combine.

$combinedArray = array_combine($people, $foods);
// $combinedArray = ['Tim' => 'chicken', 'Tony' => 'beef', 'Turanga' => 'slurm'];

Then you can loop through this by doing the same as before:

foreach ($combinedArray as $person => $meal) {
    echo "$person likes $meal\n";
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents