I want to generate a selectbox
using two arrays, one containing the country codes and another containing the country names.
This is an example:
Your code like this is incorrect as foreach only for single array:
<?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>';
}
?>
Alternative, Change to this:
<?php
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
$count = 0;
foreach($codes as $code) {
echo '<option value="' . $code . '">' . $names[count] . '</option>';
$count++;
}
?>
array_map seems good for this too
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
array_map(function ($code, $name) {
echo '<option value="' . $code . '">' . $name . '</option>';
}, $codes, $names);
Other benefits are:
If one array is shorter than the other, the callback receive null
values to fill in the gap.
You can use more than 2 arrays to iterate through.
I think that you can do something like:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
foreach ($codes as $key => $code) {
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
}
It should also work for associative arrays.
Why not just consolidate into a multi-dimensional associative array? Seems like you are going about this wrong:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
becomes:
$dropdown = array('tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France');
This worked for me:
$codes = array('tn', 'us', 'fr');
$names = array('Tunisia', 'United States', 'France');
foreach($codes as $key => $value) {
echo "Code is: " . $codes[$key] . " - " . "and Name: " . $names[$key] . "<br>";
}
foreach only works with a single 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))) {
echo '<option value="' . $code['value'] . '">' . $name['value'] . '</option>';
}
each() returns information about the current key and value of the array and increments the internal pointer by one, or returns false if it has reached the end of the array. This code would not be dependent upon the two arrays having identical keys or having the same sort of elements. The loop terminates when one of the two arrays is finished.