Skip to main content

Ways to Check if a PHP Array is Empty

TL;DR: This guide covers six methods to check if a PHP array is empty: using empty(), count(), sizeof(), isset(), array_key_exists() functions, and comparison with an empty array. Each method is explained with code examples and console outputs.

Using empty() Function

The empty() function checks if a variable is empty, including an empty array.

$array = [];
if (empty($array)) {
    echo "The array is empty";
} else {
    echo "The array is not empty";
}

Console Output

The array is empty

Using count() Function

The count() function returns the number of elements in an array.

$array = [1, 2, 3];
if (count($array) === 0) {
    echo "The array is empty";
} else {
    echo "The array is not empty";
}

Console Output

The array is not empty

Using sizeof() Function

The sizeof() function is an alias of count().

$array = [];
if (sizeof($array) === 0) {
    echo "The array is empty";
} else {
    echo "The array is not empty";
}

Console Output

The array is empty

Using isset() Function

The isset() function can be used to check if the first element of an array exists.

$array = [1, 2, 3];
if (!isset($array[0])) {
    echo "The array is empty";
} else {
    echo "The array is not empty";
}

Console Output

The array is not empty

Using array_key_exists() Function

The array_key_exists() function checks if a key exists in an array.

$array = [];
if (!array_key_exists(0, $array)) {
    echo "The array is empty";
} else {
    echo "The array is not empty";
}

Console Output

The array is empty

Comparison with Empty Array

You can compare the array with an empty array using the equality operator.

$array = [];
if ($array === []) {
    echo "The array is empty";
} else {
    echo "The array is not empty";
}

Console Output

The array is empty

Interactive Example

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!