I want to generate a selectbox
using two arrays, one containing the country codes and another containing the country names.
This is an example:
You can use array_merge to combine two arrays and then iterate over them.
$array1 = array("foo" => "bar");
$array2 = array("hello" => "world");
$both_arrays = array_merge((array)$array1, (array)$array2);
print_r($both_arrays);
Few arrays can also be iterated like this:
foreach($array1 as $key=>$val){ // Loop though one array
$val2 = $array2[$key]; // Get the values from the other arrays
$val3 = $array3[$key];
$result[] = array( //Save result in third array
'id' => $val,
'quant' => $val2,
'name' => $val3,
);
}
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.
I think the simplest way is just to use the for loop this way:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
for($i = 0; $i < sizeof($codes); $i++){
echo '<option value="' . $codes[$i] . '">' . $names[$i] . '</option>';
}
array_combine()
worked great for me while combining $_POST
multiple values from multiple form inputs in an attempt to update products quantities in a shopping cart.
Instead of foreach loop, try this (only when your arrays have same length).
$number = COUNT($_POST["codes "]);//count how many arrays available
if($number > 0)
{
for($i=0; $i<$number; $i++)//loop thru each arrays
{
$codes =$_POST['codes'][$i];
$names =$_POST['names'][$i];
//ur code in here
}
}