RE: [PHP] One more form question
| From: | Ford, Mike [LSS] | Date: | Sat, 04 Jan 2003 19:11:34 +0000 |
| Subject: | RE: [PHP] One more form question | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-130251@lists.php.net to get a copy of this message | ||
-----Original Message-----
From: David Chamberlin
To: php-general@lists.php.net
Is there an easy way to set something in a select list to be selected?
Right now I'm doing a real brute-force method. e.g.,
echo "<td><select name=\"disp_address\">";
$choices = array( 'pub' => 'On Public Page',
'members' => 'Only on Members Page',
'nodisp' => 'Do not Display' );
foreach ( $choices as $key => $choice ) {
$selected = '';
if ( strcmp( $key, $member_info->display_address ) == 0 ) {
$selected = 'selected';
}
echo "<option value=\"$key\" $selected>$choice";
}
echo '</select></td>';
--------------------------
Well, that's pretty much how to do it. I'd really only query the expense of
a call to strcmp(), rather than just doing a straight comparison. And I'd
tend to do the if in-line where required, rather than assigning to an
intermediate variable. Which gives you this:
foreach ( $choices as $key => $choice ) {
echo "<option value=\"$key\""
if ($key==$member_info->display_address) {
echo 'selected';
}
echo ">$choice</option>";
}
Actually, I often wrap the "selected" test into a ?: operator, so you get
something like this:
foreach ( $choices as $key => $choice ) {
echo "<option value=\"$key\"" .
. ($key==$member_info->display_address?'selected':'')
. ">$choice</option>";
}
Also, the suggestion of turning this whole thing into a function is a good
one, if that works for you.
Cheers!
Mike Ford