Skip to main content

Populate Dropdown List with Array Values in PHP


The below PHP function used to Populate HTML Dropdown List from Array Values.

Function :

<?php

function rnsdrop_Array($arr,$selids,$title='Select'){
    print"<option value='0'>".$title."</option>";
    foreach($arr as $id =>$name) {
    if($selids==$id && $id!=0)
        print "<option value=\"".$id."\" selected>".stripslashes($name)."</option>\r\n";
    else if($id!=0)
        print "<option value=\"".$id."\">".stripslashes($name)."</option>\r\n";
    }
}

?> 

The below example explains how to generate dropdown list with array values using simple PHP function.
 
Example:

<?php
$arr=array(0=>'-',1=>'East','West','North','South');
rnsdrop_Array($prop_facing, @$row['prop_facing'],"Select Property Facing");
?>

Output:

<select name="prop_facing" id="prop_facing" style="width: 310px" required="">
    <option value="0">Select Facing</option>
    <option value="1">East</option>
    <option value="2">West</option>
    <option value="3">North</option>
    <option value="4">South</option>
</select> 

Comments