I want to generate a selectbox
using two arrays, one containing the country codes and another containing the country names.
This is an example:
Walk it out...
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
PHP 5.3+
array_walk($codes, function ($code,$key) use ($names) {
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
});
Before PHP 5.3
array_walk($codes, function ($code,$key,$names){
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
},$names);
or combine
array_walk(array_combine($codes,$names), function ($name,$code){
echo '<option value="' . $code . '">' . $name . '</option>';
})
in select
array_walk(array_combine($codes,$names), function ($name,$code){
@$opts = '<option value="' . $code . '">' . $name . '</option>';
})
echo "<select>$opts</select>";
demo
Use array_combine() to fuse the arrays together and iterate over the result.
$countries = array_combine($codes, $names);
<?php
$codes = array ('tn','us','fr');
$names = array ('Tunisia','United States','France');
echo '<table>';
foreach(array_keys($codes) as $i) {
echo '<tr><td>';
echo ($i + 1);
echo '</td><td>';
echo $codes[$i];
echo '</td><td>';
echo $names[$i];
echo '</td></tr>';
}
echo '</table>';
?>
it works for me
$counter = 0;
foreach($codes as $code)
{
$codes_array[$counter]=$code;
$counter++;
}
$counter = 0;
foreach($names as $name)
{
echo $codes_array[$counter]."and".$name;
$counter++;
}
This will create a dropdown menu from an array and automatically assign its respective value.
<?php
$names = array('tn'=>'Tunisia','us'=>'United States','fr'=>'France');
echo '<select name="countries">';
foreach($names AS $let=>$word){
echo '<option value="'.$let.'">'.$word.'</option>';
}
echo '</select>';
?>
<select name="countries">
<?php
$countries = array('tn'=> "Tunisia", "us"=>'United States',"fr"=>'France');
foreach($countries as $select=>$country_name){
echo '<option value="' . $select . '">' . $country_name . '</option>';
}
?>
</select>
<?php
$my_array = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France'
);
echo '<select name="countries">';
echo '<option value="none">Select...</option>';
foreach ($my_array as $k => $v) {
echo '<option value="' . $k . '">' . $v . '</option>';
}
echo '</select>';
?>
I solved a problem like yours by this way:
foreach(array_keys($idarr) as $i) {
echo "Student ID: ".$idarr[$i]."<br />";
echo "Present: ".$presentarr[$i]."<br />";
echo "Reason: ".$reasonarr[$i]."<br />";
echo "Mark: ".$markarr[$i]."<br />";
}