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?
All fully tested
3 ways to create a dynamic dropdown from an array.
This will create a dropdown menu from an array and automatically assign its respective value.
Method #1 (Normal Array)
Method #2 (Normal Array)
Method #3 (Associative Array)
Few arrays can also be iterated like this:
That is not valid.
You probably want something like this...
Alternatively, it'd be much easier to make the codes the key of your
$names
array...You can use array_merge to combine two arrays and then iterate over them.
it works for me
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 thenforeach
that single array:Or as seen in the other answers, you can hardcode an associative array instead.