How to check if a variable is empty in PHP?
Use the empty() function. It returns true when the variable does not exist or has a false-like value, and false otherwise.
<?php
$a = "";
$b = "0";
$c = "Hello";
var_dump(empty($a));
var_dump(empty($b));
var_dump(empty($c));
?>
Output:
Tutorials Class - Output Window
bool(true)
bool(true)
bool(false)
These values are all empty: "", 0, 0.0, "0", null, false, [] and an undefined variable. The string “0” is a surprise for many people, so do not use empty() when 0 is a valid value.
Read the full chapter PHP empty() and the comparison isset() vs empty() vs is_null().
Learn more about the similar topics:
| Tutorials |
|---|
| PHP Variables |
| PHP Data Types |
| PHP Constants |
| PHP isset() Function |
| PHP empty() Function |
| PHP is_null() Function |
| Exercises & Assignments |
|---|
| Write a program to print “Hello PHP” using variable |
| Write a program to print a string using echo+variable. |
| Write a program to print two variables in single echo |