Potherca
10/6/2017 - 7:47 AM

Do not use `empty` for comparisons -- Potherca's rules for creating more robust code in PHP

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

Do not use 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:

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