tags:

views:

64

answers:

3

In generating a select tag for a Boolean value, I use the following code:

<select name="name" id="id">
    <option value="0"<?php if(empty($value)): ?> selected="selected"<?php endif; ?>>Off</option>
    <option value="1"<?php if($value): ?> selected="selected"<?php endif; ?>>Off</option>
</select>

So, the question is, will this map correctly, so that at no point, both the options will have a selected="selected" property?

+3  A: 

The only reason I see to use empty() here is to avoid warnings in case $value is not set. But in this case you get the warning next line. It's more common and prettier to use ! to negate booleans otherwise.

But to answer your question, yes, your assumption is safe.

Update: The documentation explicitly states that

empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.

Michael Krelin - hacker
It's worth nothing that **!** and **empty** behave somewhat odd in the event you have a value = 0 as 0 == false.
cballou
cballou, PHP redefines meaning of "odd" when it comes to matters of Truth and Falsehood. Who would have guessed the outcome of *string* comparison `'0' == '0x0'` ;-)
Michael Krelin - hacker
A: 

eInteresting. Saying that:

  • $value is the reciprocal of empty($value)

is, in my view, equivalent to asserting that

  • (bool) $value is equal to !empty($value)

In your example code $value is a bool, in which case the assertion is true (and Michael Krelin - hacker's answer that your assumption is safe is true).

But is this assertion is generally true? Considering the manual's documentation of empty(), I think it might be.

fsb
It *is*. The manual explicitly says "empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set."
Michael Krelin - hacker
Well, that is, assuming that it is safe to make assumption regarding php ;-)
Michael Krelin - hacker
We'd be in trouble if we couldn't make _this_ sort of assumption about PHP, Michael :-)
fsb
fsb, we *are* in trouble when we're doing php.
Michael Krelin - hacker
+1  A: 

(bool) $value is equivalent to !empty($value) and !$value is equivalent to empty($value). See the PHP type comparison tables for more information.

Gumbo