in PHP by (14.2k points)
0 like 0 dislike
283 views

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 (14.2k 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))) {}

Your answer

Try to answer the question as detailed as possible.
Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.