How to useempty() Function in PHP
The empty() function is a built-in PHP function that checks whether a variable is empty. A variable is considered empty if it does not exist, or if its value is equal to false, 0, “” (an empty string), “0” (a string containing zero), null, or an empty array.
<?php
$var1 = null;
$var2 = "";
$var3 = 0;
$var4 = "0";
$var5 = false;
$var6 = [];
$var7 = "Hello";
echo "Is variable 1 empty? " . (empty($var1) ? 'true' : 'false') . "\n";
echo "Is variable 2 empty? " . (empty($var2) ? 'true' : 'false') . "\n";
echo "Is variable 3 empty? " . (empty($var3) ? 'true' : 'false') . "\n";
echo "Is variable 4 empty? " . (empty($var4) ? 'true' : 'false') . "\n";
echo "Is variable 5 empty? " . (empty($var5) ? 'true' : 'false') . "\n";
echo "Is variable 6 empty? " . (empty($var6) ? 'true' : 'false') . "\n";
echo "Is variable 7 empty? " . (empty($var7) ? 'true' : 'false');
?>
Output
Is variable 1 empty? true Is variable 2 empty? true Is variable 3 empty? true Is variable 4 empty? true Is variable 5 empty? true Is variable 6 empty? true Is variable 7 empty? false
Explanation:
- The empty() function returns true if the variable is empty and false otherwise.
How to Check Whether a Variable is Empty in PHP?
Given some values of variables, the task is to check whether the variable is empty or not in PHP. An empty variable can refer to a variable that has not been set, a variable that has been explicitly set to an empty value, or a variable that contains a value that is considered empty. In this article, we will explore different approaches to check whether a variable is empty in PHP.
Table of Content
- Using empty() Function
- Using isset() Function