0
0
PhpHow-ToBeginner · 3 min read

How to Check if an Array is Empty in PHP

In PHP, you can check if an array is empty by using the empty() function or by checking if count() returns zero. Both methods return true if the array has no elements and false otherwise.
📐

Syntax

There are two common ways to check if an array is empty in PHP:

  • empty($array): Returns true if the array has no elements or is not set.
  • count($array) === 0: Returns true if the array has zero elements.
php
<?php
// Using empty()
if (empty($array)) {
    // array is empty
}

// Using count()
if (count($array) === 0) {
    // array is empty
}
?>
💻

Example

This example shows how to check if an array is empty using both empty() and count(). It prints messages based on whether the array has elements or not.

php
<?php
$array1 = [];
$array2 = [1, 2, 3];

// Check with empty()
if (empty($array1)) {
    echo "array1 is empty\n";
} else {
    echo "array1 is not empty\n";
}

// Check with count()
if (count($array2) === 0) {
    echo "array2 is empty\n";
} else {
    echo "array2 is not empty\n";
}
?>
Output
array1 is empty array2 is not empty
⚠️

Common Pitfalls

One common mistake is using isset() to check if an array is empty. isset() only checks if the variable exists and is not null, but it does not check if the array has elements.

Also, using empty() on a variable that is not an array can give unexpected results.

php
<?php
$array = [];

// Wrong: isset() returns true even if array is empty
if (isset($array)) {
    echo "Array exists, but might be empty\n";
}

// Right: use empty() or count()
if (empty($array)) {
    echo "Array is empty\n";
}
?>
Output
Array exists, but might be empty Array is empty
📊

Quick Reference

MethodDescriptionReturns true if array is empty
empty($array)Checks if variable is empty or not setYes
count($array) === 0Counts elements, checks if zeroYes
isset($array)Checks if variable exists and is not nullNo

Key Takeaways

Use empty() or count() === 0 to check if an array is empty in PHP.
isset() does not check if an array has elements, only if it exists.
empty() returns true for empty arrays and variables not set or falsey.
Checking array emptiness helps avoid errors when processing arrays.
Always ensure the variable is an array before checking to avoid unexpected results.