The Web Blinders logo

Programming

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

php generate html select values dynamically

set html select input option selected php

php array to html select input options

Need developers ?

if so, send a message.

thewebblinders@gmail.com

More Programming from our blog

SEARCH FOR ARTICLES