Beginner LevelPHP 8+
What is the difference between isset(), empty(), and is_null() in PHP?
❓ Interview Prompt: Compare variable inspection functions regarding undefined variables, null checks, and falsy values ("", 0, false, []).
In PHP, inspecting variable existence and truthiness requires understanding how these three functions handle 'null', undefined variables, and "empty" values:
1. 'isset($var)':
•
Returns 'true' if the variable exists AND is not 'null'.
•
Crucially, calling 'isset()' on an undefined variable does NOT trigger an Undefined Variable Warning! This makes it ideal for checking array keys ('isset($_GET["id"])').
2. 'empty($var)':
•
Returns 'true' if the variable is undefined, 'null', OR evaluates to a Falsy value (such as '""' empty string, '0', '0.0', '"0"' string zero, 'false', or '[]' empty array).
•
Trap: If a user submits a form input with the value '"0"' (like rating 0 stars), 'empty($_POST["rating"])' returns 'true'!
3. 'is_null($var)':
•
Returns 'true' only if the variable is explicitly 'null'.
•
If called on an undefined variable, it throws a PHP Warning / Notice!
Code Implementation Example
php
<?php
$a = null;
$b = "";
$c = 0;
$d = "0"; // String zero!
// 1. isset() checks if defined and NOT null
var_dump(isset($a)); // false (it is null)
var_dump(isset($b)); // true (string exists)
var_dump(isset($undefinedVar)); // false (no warning thrown!)
// 2. empty() checks for Falsy values
var_dump(empty($b)); // true (empty string)
var_dump(empty($c)); // true (integer 0 is empty!)
var_dump(empty($d)); // true (string "0" is empty in PHP! Be careful with form submissions!)
// 3. is_null() checks strict null equality
var_dump(is_null($a)); // true
var_dump($a === null); // true (Identical and faster than calling is_null function!)💡Comparing isset, empty, and is_null behaviors on null and falsy values.
🎯 Interview Key Takeaway
Use isset() to safely check if variables/array keys exist without warnings. Be careful with empty() on "0" and integer 0.
#isset#empty#is_null#Beginner
Back to all PHP 8+ Questions→