Do not use empty
for comparisons
A developer wants to check that a $variable
actually contains a value.
The developer does not know (or does not care) what the exact value of the variable is.
The developer decides to use empty
.
When code contains if ( ! empty($variable)) { /* ... */}
what actually happens
is:
if (
$variable !== "" // an empty string
&& $variable !== 0 // 0 as an integer
&& $variable !== 0.0 // 0 as a float
&& $variable !== "0" // 0 as a string
&& $variable !== NULL
&& $variable !== FALSE
&& $variable !== array() // an empty array
// && ! (variable declared but without a value)
) {
/* ... */
}
Furthermore, empty()
does not generate a warning if the variable does not exist.
The empty
function incorporates several checks. From the function name it is
not clear what "empty" means. To be certain a developer will have to look the
exact working up in the manual.
This is a classic case of hidden complexity. The code may look simple but it is not as simple as it looks.
Use a more strict and declarative check.
- But now my
if
is verbose and ugly! Usingempty
keeps it short and simple.
To have the check be simple without usingempty
see [Use function calls inif
statements].
- Be explicit
- Do not hide complexity
- PHP manual entry on
empty
http://php.net/manual/en/function.empty.php