phparraysforeachsynchronous

Synchronously iterate and print values from two arrays of the same size


I want to generate a selectbox using two arrays, one containing the country codes and another containing the country names.

This is an example:

$codes = ['tn', 'us', 'fr'];
$names = ['Tunisia', 'United States', 'France'];

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

This method didn't work for me. Any suggestions?


Solution

  • 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',
       ...
    );