View Single Post
  #3 (permalink)  
Old 03-02-2008, 05:14 AM
BigAlReturns's Avatar
BigAlReturns BigAlReturns is offline
Moderator Extraordinaire!
 
Join Date: Dec 2007
Location: The Wirral, England
Posts: 291
Send a message via MSN to BigAlReturns
Default

There's an attenuated version of if else syntax that makes for much clearer reading, the basic format is:
Code:
(statement) ? "return if true" : "return if false";
e.g.
echo ($bla==$colour) ? 'selected' : 'not selected';
You can also use the selected attribute of an option tag to determine which is initially selected, i.e.:
Code:
<option value="red" selected="selected">Red</option>
So in your case it would look something like this:
Code:
    <select name="bla">
       <option value="red" selected="<?php echo ($bla=="red") ? 'selected="selected"';?>">Red</option>
<option value="green" selected="<?php echo ($bla=="green") ? 'selected="selected"';?>">Green</option>
<option value="blue" selected="<?php echo ($bla=="blue") ? 'selected="selected"';?>">Blue</option>
</select>
Another, probably more elegant, and definitely more extensible way to do this is to store colour options in an array, and loop through this array to create the options:
Code:
<select>
<?php
$colours=array('red','blue','green');
FOREACH ($colours AS $colour) {
$selector = ($bla==$colour) ? 'selected="selected"' : '';
echo '<option value="' . $colour . '"' . $selected . '>' . $colour . ' </option>';
}
?>
</select>
The first method is easier on the eye, but the method in this post means you can easily add or remove options, and easily fill the options dynamically, say from a database.

As for the refresh issue, I personally don't worry about it - it's unlikely to occur very often. If you did really need to do it, then IP address won't work, because not only can it change, but people can share IPs as well. The way forward with this would be to use sessions.
Reply With Quote