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 Quote Link to comment 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>"; } Quote Link to comment 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; ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.