Comparison of isset(), empty(), and is_null() in PHP
Function | Checks if Variable Exists | Checks if Variable is Empty | Checks if Variable is NULL |
isset() | Yes | No | No |
empty() | Yes | Yes (and other conditions*) | No |
is_null() | No | No | Yes |
For empty(), a variable is considered empty if it doesn't exist, or its value equals false, 0, an empty string '', NULL, an empty array, or an object with no properties.
Examples:
$var1 = '';
$var2 = null;
$var3 = 0;
$var4 = false;
echo "isset() Examples:\n";
echo "var1: " . (isset($var1) ? 'set' : 'not set') . "\n"; // set
echo "var2: " . (isset($var2) ? 'set' : 'not set') . "\n"; // not set
echo "\nempty() Examples:\n";
echo "var1: " . (empty($var1) ? 'empty' : 'not empty') . "\n"; // empty
echo "var2: " . (empty($var2) ? 'empty' : 'not empty') . "\n"; // empty
echo "var3: " . (empty($var3) ? 'empty' : 'not empty') . "\n"; // empty
echo "var4: " . (empty($var4) ? 'empty' : 'not empty') . "\n"; // empty
echo "\nis_null() Examples:\n";
echo "var1: " . (is_null($var1) ? 'null' : 'not null') . "\n"; // not null
echo "var2: " . (is_null($var2) ? 'null' : 'not null') . "\n"; // null
Output:
isset() Examples:
var1: set
var2: not set
empty() Examples:
var1: empty
var2: empty
var3: empty
var4: empty
is_null() Examples:
var1: not null
var2: null
In summary:
- isset() checks if a variable exists.
- empty() checks if a variable is empty.
- is_null() checks if a variable is NULL.