user2318128
user2318128

Reputation: 109

how to set select box default value in php

<?php
$options = array('volvo'=>'Volvo', 'saab' =>'Saab', 'audi' => 'Audi' );
echo "<select name='sss'>\n";
foreach ($options as $k=>$v) echo "<option value='$v' >$k</option>\n";
echo "</select>\n";
?>

Question:

how to make 'audi' as the default value instead of 'volvo'? I know we can set 'selected' in html, but how could i do it in this php script?

Upvotes: 5

Views: 7570

Answers (3)

prash.patil
prash.patil

Reputation: 687

Try this:

$options = array('volvo'=>'Volvo', 'saab' =>'Saab', 'audi' => 'Audi' );
$select_value = 'audi';

<select id="test" name="test">
<?php foreach($option as $row) {?>
    <option value="<?php echo $row?>" <?php echo (strcmp($select_value,$row)==0) ?"selected='selected":'' ?>><?php echo $row?></option>
  <?php } ?>
</select>

Upvotes: 0

Orangepill
Orangepill

Reputation: 24645

I usually create a helper function for outputing selects

function showSelect($name, $options, $selected, $attr = array()){
    $str = "<select name='".$name.'"';
    foreach($attr as $name=>$val){
        $str.= " ".$name."='".$val."'";
    }
    $str.=">";
    foreach($options as $k=>$val){
        $str.= "<option value='".$val."'".($val==$selected?" selected='selected'":"").">".$k.'</option>';
    }
    $str.="</select>";
    return $str;
}

then to call just

echo showSelect("sss", $options, "audi", array("id"=>"manufacturer"));

Upvotes: 2

Mark Elliot
Mark Elliot

Reputation: 77054

You could detect if the default value is the one you want and insert the HTML you already identified:

$defaultVal = 'Audi';
foreach ($options as $k=>$v) {
    $selected = ($v == $defaultVal) ? " selected='selected'" : "";
    echo "<option value='$v'$selected>$k</option>\n";
}

Upvotes: 6

Related Questions