Making a preselected drop-down selection box in HTML

Posted on


I’m a PHP newbie and I have a question. Is there a better way to do this? A nice solution?

$list = isset($_GET['list']) ? htmlspecialchars($_GET['list']) : "experience";

<select name="type" id="type">
<option value="experience">Experience</option>
<option value="magic"<?=$list == "magic" ? 'selected' : '';?>>Magic Points</option>
<option value="shielding"<?=$list == "shielding" ? 'selected' : '';?>>Shielding</option>
<option value="distance"<?=$list == "distance" ? 'selected' : '';?>>Distance</option>
<option value="melee"<?=$list == "sword" ? 'selected' : '';?>>Melee</option>
<option value="fishing"<?=$list == "fishing" ? 'selected' : '';?>>Fishing</option>


You can use a lookup table for your values like this:

$values = array("magic" => "Magic points", ...);

and then loop over that to reduce the duplication:

foreach ($values as $key => $value) {

You might want to build a wrapper for this.

$output->add_select(array $fields, $id, $name, $multichoice = false) {

    $html = "<select name='$type' id='type'>";

    foreach ($fields AS $field){

    return $html;


You get the idea. There is nothing more convenient hat having all those form-gruntworks in methods.

$output->add_select($this->get_powers(), 'power', 'power')); or alike and you are good to go.

Leave a Reply

Your email address will not be published. Required fields are marked *