in PHP by (15.1k points)
0 like 0 dislike

I want to use two arrays in PHP foreach loop - one array containing names and another array containing numbers. How I can to use two arrays in one foreach loop in PHP?

Variants for example:

foreach ($numbers as $number and $names as $name) {}
foreach ($numbers as $number; $names as $name) {}
foreach ($numbers, $names as $number, $name) {}

All this methods didn't work for me. Any suggestions?

php foreach with two arrays

1 Answer

0 like 0 dislike
by (15.1k points)

All that is not valid. Foreach loop operates on only one array at a time, i.e. foreach loop only works with a single array.

You can use array_combine() function for convert them into an array of key-value pairs, then foreach that single array:

foreach (array_combine($codes, $names) as $number => $name) {}

Or you can an associative array instead, i.e. you can do something like this:

foreach ($codes as $index => $code) {}

Alternatively, it'd be much easier to make the codes the key of your $names array.

To step through multiple arrays, it's better to use the each() function in a while loop:

while (($code = each($codes)) && ($name = each($names))) {}

Please log in or register to answer this question.