Home » Programming » PHP » Php Empty

How to Use the PHP empty() Function

This easy tutorial will show you how to use the PHP empty() function to check whether a variable can be considered empty and show some code examples.

What Is Empty?

A variable is considered empty in PHP if its value equates to FALSE or the variable does not exist.

This means that the following are considered empty:

  • An empty string (“”)
  • The number zero (0)
    • In any form (0.0000)
    • Including strings containing only a 0 character (“0”)
  • Boolean FALSE
  • NULL
  • An undeclared variable
  • Empty arrays

The empty() function is different from the isset() function. The latter checks only whether a variable is declared and not null.

PHP empty() Function Syntax

The syntax for the empty() function is as follows:

empty(VAR)

Note that:

  • VAR should be the variable to be checked for emptiness
  • empty() will return a boolean value (TRUE or FALSE)
    • TRUE if the passed VAR is empty
    • FALSE if it is not
  • If the variable *VAR has not been declared, no error will be thrown!
    • FALSE will be returned instead

Php empty() Function Examples

$var = NULL;
if(empty($var)) echo $var . ' is empty!\n';

$var = '0';
if(empty($var)) echo $var . ' is empty!\n';

$var = 0;
if(empty($var)) echo $var . ' is empty!\n';

$var = '';
if(empty($var)) echo $var . ' is empty!\n';

$var = "";
if(empty($var)) echo $var . ' is empty!\n';

$var = null;
if(empty($var)) echo $var . ' is empty!\n';

$var = [];
if(empty($var)) echo json_encode($var) . ' is empty!\n'; // The array is JSON encoded so it can be printed

$var = (object)[]; // Creates an empty object
if(empty($var)) echo json_encode($var) . ' is empty!\n'; // The object is JSON encoded so it can be printed

$var = FALSE;
if(empty($var)) echo $var . ' is empty!\n';

Notice that the empty object is not considered empty by isempty()!

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment