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:

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

Feedback about page:

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


Array iteration:
* Iterating multiple arrays together

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
79 Array iteration
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR