Two arrays in foreach loop Two arrays in foreach loop php php

Two arrays in foreach loop


foreach( $codes as $code and $names as $name ) { }

That is not valid.

You probably want something like this...

foreach( $codes as $index => $code ) {   echo '<option value="' . $code . '">' . $names[$index] . '</option>';}

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

$names = array(   'tn' => 'Tunisia',   'us' => 'United States',   ...);


foreach operates on only one array at a time.

The way your array is structured, you can array_combine() them into an array of key-value pairs then foreach that single array:

foreach (array_combine($codes, $names) as $code => $name) {    echo '<option value="' . $code . '">' . $name . '</option>';}

Or as seen in the other answers, you can hardcode an associative array instead.


Use array_combine() to fuse the arrays together and iterate over the result.

$countries = array_combine($codes, $names);