Mundo Posted July 20, 2010 Share Posted July 20, 2010 I'm a little stuck... Say the URL is http://ilovecars.com/index.php?car=Volvo and I have a loop which outputs my options such as: <option value="$car">$car</option> I want to have the car which is selected (in this case volvo) selected in the list. For example: <option value="$car" selected="selected">$car</option> Obviously I don't want "selected" on the rest of the listbox... How could I get PHP to do that? Many thanks for any help Link to comment https://forums.phpfreaks.com/topic/208283-php-and-option-select/ Share on other sites More sharing options...
TheEvilMonkeyMan Posted July 20, 2010 Share Posted July 20, 2010 Inside your loop where you print out all the <option>s, check if $car is equal to $_GET['car'] and, if so, print out selected="selected" in your tag otherwise print it out without. if($car == $_GET['car']) { echo "<option value=\"$car\" selected=\"selected\">$car</option>"; } else { echo "<option value=\"$car\">$car</option>"; } Link to comment https://forums.phpfreaks.com/topic/208283-php-and-option-select/#findComment-1088543 Share on other sites More sharing options...
Wolphie Posted July 20, 2010 Share Posted July 20, 2010 Personally I'd be more inclined to do something like: $car = $_GET['car']; $cars = array('Volvo', 'Ford', 'Nissan', 'Toyota'); $select = '<select name="cars">'; foreach ($cars as $key => $val) { $select .= '<option value="'. $val .'"'; if (isset($car) && $car == $val) { $select .= ' selected="selected"'; } $select .= '>'. $val .'</option>'; } $select .= '</select>'; echo $select; ?> Link to comment https://forums.phpfreaks.com/topic/208283-php-and-option-select/#findComment-1088549 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.