W3docs

empty

The "empty" keyword is a function in PHP that is used to determine whether a variable is empty. In this article, we will explore the syntax and usage of the

The PHP empty() Language Construct: A Comprehensive Guide

The empty() language construct in PHP is used to determine whether a variable is considered empty. In this article, we will explore the syntax and usage of empty() in depth, and provide plenty of examples to help you master this important PHP feature.

Syntax

The empty() construct checks if a variable is empty. Here is the basic syntax:

The PHP syntax of empty()

<?php

if (empty($variable)) {
  // variable is empty
}

In this example, empty($variable) evaluates to true if the variable is empty, and false otherwise.

The following values are considered empty by empty():

  • null
  • "" (empty string)
  • 0 or "0" (integer or string zero)
  • false
  • [] (empty array)

Note: empty() returns true for undefined variables without triggering a warning.

Examples

Let's look at some practical examples of how the empty() construct can be used:

Examples of PHP empty()

<?php

// Example 1
$myVariable = "";
if (empty($myVariable)) {
  echo "Variable is empty" . PHP_EOL;
} else {
  echo "Variable is not empty";
}

// Output: Variable is empty

// Example 2
$myArray = [];
if (empty($myArray)) {
  echo "Array is empty";
} else {
  echo "Array is not empty";
}

In these examples, we use the empty() construct to determine whether a variable is empty.

Comparison with isset() and is_null()

It is important to distinguish empty() from similar constructs:

  • isset($var) returns false only if the variable is null or unset. It returns true for empty strings, 0, or empty arrays.
  • is_null($var) returns true only if the variable's value is exactly null.
  • empty($var) returns true for a broader set of falsy states, including null, "", 0, "0", false, and [].

Benefits

Using the empty() construct has several benefits, including:

  • Improved code functionality: The empty() construct helps verify variable states, making validation logic more robust.
  • Simplified code: It allows you to check for multiple empty or falsy states in a single call, reducing the need for complex conditional chains.

Conclusion

In conclusion, the empty() construct is a powerful tool for PHP developers, allowing them to determine whether a variable is empty and improve the functionality and readability of their code. We hope this comprehensive guide has been helpful, and we wish you the best of luck as you continue to develop your PHP skills.

Practice

Practice

What does empty() do in PHP?