MOCKSTACKS
EN
Questions And Answers

More Tutorials









PHP Array iteration


Iterating multiple arrays together


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);

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


Conclusion

In this page (written and validated by ) you learned about PHP Array iteration . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP Datetime Class.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.