What is the empty() function in PHP?

Overview

The PHP programming language holds a very large set of built-in functions. A very common function in this set is the empty function. You can use the empty function to check if a variable has a value or not.

Empty vs. NULL

When you declare a variable, you are simply telling the computer system to reserve a space in memory where data can be saved. With the provided variable name, you can map a physical location in memory to a logical address that serves as a pointer.

Now, when a variable is empty, it simply means that it points to a memory location that has a length of zero or contains no value. An empty variable implies that this logical address, the variable name, is bound to a physical address that has no value at all.

Meanwhile, when a variable is NULL, it simply means that the variable name (the logical address) is pointing to nowhere, as it hasn’t been bound to a physical location.

Examples

The PHP code and image below will give more insight into the differences between empty and null.

//This string is empty
 $empVar = "";

//This is Null
$nullVar;

Syntax

empty($variable);

Parameters

The empty() function only accepts a single parameter, which is the variable to be checked.

Return value

The empty() function returns true if the value is empty or has a zero value; otherwise, it returns false.

Code

<?php
// empty integer value
$var1 = 0;
// a null value
$var2;
//checking data type of $var2
echo gettype($var1) ."\n";
// Evaluates to true because $var1 is empty
if (empty($var1)) {
echo '$var1 is either 0, empty, or not set at all'."\n";
}
//checking data type of $var2
echo gettype($var2) ."\n";
// Evaluates as false because $var2 is null not empty
if (empty($var2)) {
echo '$var2 is set even though it is empty';
}
?>

Take a look at the code snippet above. You will notice that $var2 of data type NULL returns true when checked if it was empty. This simply means that all NULL data type values in PHP are considered empty, but not all empty variables are NULL. In the example above, $var1 is of data type integer.

Free Resources