Tuesday, November 01, 2011

PHP [NO-IF]: Make option selected

Technique for make option selected without IF statement.

[php]
//came from anywhere: post, get, cookie, etc.
$color_selected = 'red';

//Required if works in a strict environment
$colors = array(
  'blue' => null,
  'red' =>  null,
  'white' => null,
);

//Only set selected color
$colors[$color_selected] = 'selected="selected"';

echo <<<PQR
What Color?
<select name="color">
    <option value="blue" {$colors['blue']}>Blue</option>
    <option value="red" {$colors['red']}>Red</option>
    <option value="white" {$colors['white']}>White</option>
</select>
PQR;

[/php]

No comments: