I don't see how if(!empty($var)) can create confusion, but I do agree that if ($var) is simpler. – vanneto Mar 8 '12 at 13:33
Because empty has the specific purpose of suppressing errors for nonexistent variables. You don't want to suppress errors unless you need to. The Definitive Guide To PHP's isset And empty explains the problem in detail. – deceze♦ Mar 9 '12 at 1:24
Focusing on the error suppression part, if the variable is an array where a key being accessed may or may not be defined:
if($web['status']) would produce:
Notice: Undefined index: status
- To access that key without triggering errors:
if(isset($web['status']) && $web['status']) (2nd condition is not tested if the 1st one is FALSE) OR
if(!empty($web['status'])).
However, as deceze♦ pointed out, a truthy value of a defined variable makes !empty redundant, but you still need to remember that PHP assumes the following examples as FALSE:
null
'' or ""
0.0
0
'0' or "0"
'0' + 0 + !3
So if zero is a meaningful status that you want to detect, you should actually use string and numeric comparisons:
Error free and zero detection:
if(isset($web['status'])){
if($web['status'] === '0' || $web['status'] === 0 ||
$web['status'] === 0.0 || $web['status']) {
// not empty: use the value
} else {
// consider it as empty, since status may be FALSE, null or an empty string
}
}
The generic condition ($web['status']) should be left at the end of the entire statement.