Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
February 15, 2009, 2:23 am
rate this thread
The way I am doing it right now is with the ternary operator like so
$col = 2; //set dynamically elsewhere, just for example
<option value="blue" <?= ($col == 1) ? "selected" : ""; ?> >blue</
<option value="red" <?= ($col == 2) ? "selected" : ""; ?> >red</
I'd like a cleaner looking way to do it. Suggestions?
Re: Select Boxes: How to set a selection with PHP
Perhaps not necessarily cleaner, but more flexible (if you want to add
options, that is); untested:
$chosen = isset( $_POST[ 'color' ] ) ? intval( $_POST[ 'color' ] ) : null;
$options = array( 'red', 'blue', 'green', 'white', 'black' );
$select = '<select name="color">';
foreach( $options as $value => $label )
$selected = $value == $chosen ? ' selected="selected"' : '';
$select .= '<option value="' . $value . '"' . $selected . '>' .
$label . '</option>';
$select .= '</select>';
then somewhere in your html:
<?php echo $select; ?>