Chris par
Chris par

Reputation: 65

load select box with a selected option using php

Hi I have come across a problem now I do have a solution however it involves many of if statements and I would like to know it there is a neater option

what I would like is

<select>
<option value ="00:00">00:00</option>
<option value ="01:00">01:00</option>
<option value ="02:00">02:00</option>
<option value ="03:00">03:00</option>
</select> 

then get an value from and have that box selected what I'm am currently thinking is

$selectedbox = array();
if($tablevalue == "00:00"){
$selectedbox[0] = 'selected="selected"';
}
if($tablevalue == "01:00"){
$selectedbox[1] = 'selected="selected"';
}

then have

<select>
<option value ="00:00" <?php echo $selectedbox[0]; ?>>00:00</option>
<option value ="01:00" <?php echo $selectedbox[1]; ?>>01:00</option>
<option value ="02:00" <?php echo $selectedbox[2]; ?>>02:00</option>
<option value ="03:00" <?php echo $selectedbox[3]; ?>>03:00</option>
</select>

is there an easier way of getting the same result

Upvotes: 1

Views: 1333

Answers (3)

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15311

I would get rid of the if statements and put the code inline with the option tag with a ternary. Ex:

<select>
<option value ="00:00" <?=$tablevalue=="00:00"?'selected="selected"':''?>>00:00</option>
<option value ="01:00" <?=$tablevalue=="01:00"?'selected="selected"':''?>>01:00</option>
<option value ="02:00" <?=$tablevalue=="02:00"?'selected="selected"':''?>>02:00</option>
<option value ="03:00" <?=$tablevalue=="03:00"?'selected="selected"':''?>>03:00</option>
</select>

Upvotes: 1

Charles
Charles

Reputation: 4538

Take a look at PHP switch statements: http://php.net/manual/en/control-structures.switch.php

I think you would want something like this:

switch ($tablevalue) {
    case "00:00":
        $selectedbox[0] = 'selected="selected"';
        break;
    case "01:00":
        $selectedbox[0] = 'selected="selected"';
        break;
    //etc, etc
}

PHP switch is a better way to handle if statements if you're always comparing the same variable.

Upvotes: -1

Marc B
Marc B

Reputation: 360782

for ($i = 0; $i <= 3; $i++) {
    $sel = ("0{$i}:00" == $tablevalue) ? ' selected="selected"' : '';
    echo <<<EOL
<option value="0{$i}:00"{$sel}>0{$i}:00</option>

EOL;
}

Upvotes: 2

Related Questions