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?
Walk it out...
PHP 5.3+
Before PHP 5.3
or combine
in select
demo
I think the simplest way is just to use the for loop this way:
foreach only works with a single array. To step through multiple arrays, it's better to use the each() function in a while loop:
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.
I solved a problem like yours by this way:
This worked for me:
Instead of foreach loop, try this (only when your arrays have same length).