<kbd>
ℹ️ This document is part of
<a href="https://gist.github.com/Potherca/9afb08c7cf1beab383564902bbe67be3">
Potherca's Rules for creating more robust code in PHP
</a>
</kbd>
# Do not use [`empty`][php-empty] for comparisons
## Description
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`.
## Workings
When code contains `if ( ! empty($variable)) { /* ... */}` what actually happens
is:
```php
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.
## Rational
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.
## Alternatives
Use a more strict and declarative check.
## Counter arguments (and response)
- **But now my `if` is verbose and ugly! Using `empty` keeps it short and simple.**
To have the check be simple without using `empty` see **[Use function calls in `if` statements]**.
## Relevant rules
- Be explicit
- Do not hide complexity
## Resources
- PHP manual entry on `empty` [http://php.net/manual/en/function.empty.php][php-empty]
[php-empty]: http://php.net/manual/en/function.empty.php