Loading

PHP is_null() VS isset() VS empty() cheat sheet

Because sometimes things aren’t so obvious, I decided to share my true table.

  • is_null – Finds whether a variable is NULL
  • isset – Determine if a variable is declared and is different than NULL
  • empty – Determine whether a variable is empty
  • isEmpty() – Determine whether a variable is empty (0 and “0” are considered not empty)
  • if () – The if statement
True table

isEmpty()

Does PHP’s empty() function confuse you? I am now using isEmpty() and it seems to work fine (0 and “0” are considered not empty).

/**
 * Helper class | General-purpose utility class
 */
class Helper
{
    /**
     * Determine whether a variable is empty.
     * 0 and "0" are considered not empty.
     *
     * @param mixed $value Value to be checked.
     *
     * @return boolean
     */
    public static function isEmpty(&$value): bool
    {
        if ($value === 0 || $value === '0') {
            return false;
        }

        return !$value;
    }
}

See example on repl.it at https://repl.it/@SandroMiguel/isset-vs-isnull-vs-empty


Did you find it interesting? Follow me on Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *