Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set select box default value in php

Tags:

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?

like image 941
user2318128 Avatar asked May 22 '13 03:05

user2318128


1 Answers

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";
}
like image 197
Mark Elliot Avatar answered Sep 22 '22 14:09

Mark Elliot