Two arrays in foreach loop
I want to generate a selectbox
using two arrays, one containing the country codes and another containing the country names.
This is an example:
<?php
$codes = array('tn','us','fr');
$names = array('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?
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);
Use an associative array:
$code_names = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France');
foreach($code_names as $code => $name) {
//...
}
I believe that using an associative array is the most sensible approach as opposed to using array_combine()
because once you have an associative array, you can simply use array_keys()
or array_values()
to get exactly the same array you had before.