0
0
PHPprogramming~5 mins

Isset, empty, and is_null behavior in PHP

Choose your learning style9 modes available
Introduction

These functions help check if a variable exists, is empty, or is null. They make your code safer and avoid errors.

Before using a variable to make sure it exists.
To check if a form input is empty before processing it.
To find out if a variable has no value or is set to null.
When you want to avoid warnings from undefined variables.
To decide if you should assign a default value to a variable.
Syntax
PHP
isset(mixed $var): bool
empty(mixed $var): bool
is_null(mixed $var): bool

isset returns true if the variable exists and is not null.

empty returns true if the variable is empty (like 0, '0', '', null, false, or not set).

Examples
Variable $a is set to 5, so isset is true, empty is false, and is_null is false.
PHP
$a = 5;
isset($a); // true
empty($a); // false
is_null($a); // false
Variable $b is set to null, so isset is false, empty is true, and is_null is true.
PHP
$b = null;
isset($b); // false
empty($b); // true
is_null($b); // true
Variable $c is not set, so isset is false, empty is true, but is_null causes a warning if used.
PHP
unset($c);
isset($c); // false
empty($c); // true
// is_null($c) gives warning if $c not defined
Sample Program

This program shows how isset, empty, and is_null behave with different variable states: zero, null, and undefined.

PHP
<?php
$a = 0;
$b = null;
// $c is not set

echo "isset($a): " . (isset($a) ? 'true' : 'false') . "\n";
echo "empty($a): " . (empty($a) ? 'true' : 'false') . "\n";
echo "is_null($a): " . (is_null($a) ? 'true' : 'false') . "\n";

echo "isset($b): " . (isset($b) ? 'true' : 'false') . "\n";
echo "empty($b): " . (empty($b) ? 'true' : 'false') . "\n";
echo "is_null($b): " . (is_null($b) ? 'true' : 'false') . "\n";

echo "isset($c): " . (isset($c) ? 'true' : 'false') . "\n";
echo "empty($c): " . (empty($c) ? 'true' : 'false') . "\n";
// echo "is_null($c): " . (is_null($c) ? 'true' : 'false') . "\n"; // Warning if uncommented
?>
OutputSuccess
Important Notes

empty treats 0, '0', false, null, '', and undefined variables as empty.

isset returns false if the variable is null or not set.

Using is_null on an undefined variable causes a warning, so check with isset first.

Summary

isset checks if a variable exists and is not null.

empty checks if a variable is empty or not set.

is_null checks if a variable is exactly null.