PHP Keywords: empty()

16 February 2019 - 4:13am

Welcome to my series on every PHP keyword and its usage. Today's item: empty().

Arguably this should have been named isEmpty(), as it simply checks if a variable is "empty", rather than modifying it. Also, note that if the variable is undefined, PHP will not display a warning when used inside of empty().

In the world of PHP, "empty" could mean the variable has not been set, has not been defined or has one of the following values:

  • ""
  • 0
  • 0.0
  • "0"
  • null
  • false
  • []

Due to the ambiguity here, I'd probably recommend your code be slightly more verbose to make it unambiguous what you're expecting, and what you're checking for. If your variable is a string, for instance:

<?php
if(($_POST["name"] ?? "") === "")
{
    // Do your thing
}

Usage

<?php
// Note: If the name is "", this condition will trigger as expected.
// However, it will also trigger if the name is "0".
if(empty($_POST["name"]))
{
    // Do your thing
}