PHP Iterating multiple arrays together


Example

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:

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

which will output:

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";
}

Separate arrays can only be looped through if they are the same length and also have the same key name. This means if you don't supply a key and they are numbered, you will be fine, or if you name the keys and put them in the same order in each array.

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";
}