Do not use empty
for comparisons -- Potherca's rules for creating more robust code in PHP
ℹ️ This document is part of Potherca's Rules for creating more robust code in PHP
empty
for comparisonsA 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.
if
is verbose and ugly! Using empty
keeps it short and simple. empty
see [Use function calls in if
statements].empty
http://php.net/manual/en/function.empty.php