in this tutorial, I’ll show you how to check if an element has been defined and see if it is empty or null. This php tutorial help to understand difference between PHP isset() vs empty() vs is_null().
These methods are used to determine a variable’s value. To see if a variable has a value, use the functions isset(), empty(), and is null().
The functions isset(), empty(), and is null() are PHP built-in functions that are used to check the value of a variable or its initialization. All these functions return a Boolean value. Here, I will explain the differences between these functions.
Function Difference Table
<div class="table-wrapper"> <table class="fl-table"> <thead> <tr> <th>Method Name</th> <th>""</th> <th>"phpflow"</th> <th>NULL</th> <th>FALSE</th> <th>0</th> <th>undefined</th> </tr> </thead> <thead></thead> <tbody> <tr> <td><strong><em>empty()</em></strong></td> <td>TRUE</td> <td>FALSE</td> <td>TRUE</td> <td>TRUE</td> <td>TRUE</td> <td>TRUE</td> </tr> <tr> <td><strong><em>is_null()</em></strong></td> <td>FALSE</td> <td>FALSE</td> <td>TRUE</td> <td>FALSE</td> <td>FALSE</td> <td>ERROR</td> </tr> <tr> <td><strong><em>isset()</em></strong></td> <td>TRUE</td> <td>TRUE</td> <td>FALSE</td> <td>TRUE</td> <td>TRUE</td> <td>FALSE</td> </tr> </tbody> </table> </div>
PHP isset() Function
This isset()
method used to determine if a variable is set and is not NULL. You can read isset() docs.
This function returns the result as a Boolean value True or False.
Syntax:
isset(variable);
Example of PHP isset() Function
$age = 0; // Evaluates as true because $age is set if (isset($age)) { echo '$age is set even though it is empty'; }
Output:
$age is set even though it is empty
PHP empty() Function
The empty() is also an in-built method that is used to determine if a variable is set and not empty.
If the value is an empty string, false, array(), NULL, 0, and an unset then empty() function returns TRUE and if a value is not empty then it returns FALSE.
Syntax:
empty( $variable )
PHP empty() example
$age = 0; // Evaluates to true because $age is empty if (empty($age)) { echo '$age is either 0, empty, or not set at all'; }
Output :
$age is either 0, empty, or not set at all
PHP is_null() Method
The is_null() method used to check whether a variable is NULL or not.
This method returns the result as a Boolean value TRUE or FALSE.
Syntax:
is_null( $variable )
Example of PHP is_null() Function
$age = null; echo "age is " . is_null($age) . "<br>";
Output :
bool(true)