PHP Generating HTML Select input options
This code comes handy for generating dynamic select inputs like country list , state list , international codes etc. Additionally, you can specify which options needs to be selected by default.
<?php
$arr=[
1 => "Male",
2 => "Female",
3 => "Others"
];
function HTMLSelectOptionsGenerate($optionsArr, $optionValue , $name){
$options='';
foreach ($optionsArr as $key => $value) {
if($key == $optionValue) {
$options=<<<OPTIONS
{$options}
<option selected="selected" value="{$key}">{$value}</option>
OPTIONS;
}
else{
$options=<<<OPTIONS
{$options}
<option value="{$key}">{$value}</option>
OPTIONS;
}
}
return "
<select name='{$name}'>
{$options}
</select>";
}
echo HTMLSelectOptionsGenerate($arr,2,"gender");
/*
<select name='gender'>
<option value="1">Male</option>
<option selected="selected" value="2">Female</option>
<option value="3">Others</option>
</select>
*/
?>
ALTERNATE TITLES