PHP empty() Function

To check whether a variable is empty in PHP, you can use the “empty()” function. 

Syntax

bool empty ($var)

Parameters

 $var(required): This variable is being checked.

Return Value

It returns FALSE when $var exists and has a non-empty(non-zero value) Otherwise, it returns TRUE.

These values are considered to be an empty value:

  1. “(an empty string)
  2. 0 (0 as an integer)
  3. 0.0 (0 as a float)
  4. “0” (0 as a string)
  5. NULL
  6. FALSE
  7. array() (an empty array)

If you have declared a variable and are not given any value, this will still be considered empty.

Visual Representation of Check if an Array is EmptyVisual Representation of PHP empty() FunctionVisual Representation_2 of PHP empty() Function

Example 1: How to use empty() Function

<?php

$var = '';
$var2 = 0;
$var3 = 0.0;
$var4 = NULL;
$var5 = FALSE;
$var6 = '0';


if(empty($var)) {
 echo '$var has an empty value'."\n";
}
else {
 echo '$var has a non-empty value'."\n";
}
if(empty($var2)) {
 echo '$var2 has an empty value'."\n";
}
else {
 echo '$var2 has a non-empty value'."\n";
}
if(empty($var3)) {
 echo '$var3 has an empty value'."\n";
}
else {
 echo '$var3 has a non-empty value'."\n";
}
if(empty($var4)) {
 echo '$var4 has an empty value'."\n";
}
else {
 echo '$var4 has a non-empty value'."\n";
}
if(empty($var5)) {
 echo '$var5 has an empty value'."\n";
}
else {
 echo '$var5 has a non-empty value'."\n";
}
if(empty($var6)) {
 echo '$var6 has an empty value'."\n";
}
else {
 echo '$var6 has a non-empty value'."\n";
}

Output

$var has an empty value
$var2 has an empty value
$var3 has an empty value
$var4 has an empty value
$var5 has an empty value
$var6 has an empty value

Example 2: Check if an Array is EmptyVisual Representation of Check if an Array is Empty

<?php

$arr = [];

if(empty($arr)) {
 echo '$arr is empty';
}
else {
 echo '$arr is not empty';
}

Output

$arr is empty

Example 3: Check if an Object is Empty

Let’s define the empty class, create an object, and then check it with an empty() function.

<?php

class App {
}

$data = new App();

if(empty($data)) {
  echo 'Class is empty';
}
else {
  echo 'Class is not empty';
}

Output

Class is not empty 

That means that $data is not empty, and some properties are there.

1 thought on “PHP empty() Function”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.