In PHP, Is "if($value)" the reciprocal of "if(empty($value))"?
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)): ?>开发者_JS百科; 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?
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.
(bool) $value
is equivalent to !empty($value)
and !$value
is equivalent to empty($value)
. See the PHP type comparison tables for more information.
eInteresting. Saying that:
$value
is the reciprocal ofempty($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.
精彩评论