Current Location: Home> Latest Articles> Practical Methods to Check if an Array is Empty in PHP

Practical Methods to Check if an Array is Empty in PHP

gitbox 2025-07-17

Overview

In PHP programming, arrays are a commonly used data structure. Checking whether an array contains any elements, i.e., whether it is empty, is a frequent requirement. This article introduces several practical and common methods to check if an array is empty in PHP, helping you handle related tasks with ease.

Common Methods to Check if an Array is Empty

Using the empty Function

The empty() function can detect whether a variable is empty. When passing an array as the argument, it returns true if the array is empty, otherwise false. Example code:

$array = array();
if (empty($array)) {
  echo 'Array is empty';
} else {
  echo 'Array is not empty';
}

Using the count Function

The count() function returns the number of elements in an array. If the array is empty, it returns 0, which can be used to determine if the array is empty. Example code:

$array = array();
if (count($array) == 0) {
  echo 'Array is empty';
} else {
  echo 'Array is not empty';
}

Using the is_array Function

The is_array() function checks whether a variable is an array. It is useful to confirm a variable is an array before using count() or empty() to avoid errors. Example code:

$array = array();
if (is_array($array) && count($array) == 0) {
  echo 'Array is empty';
} else {
  echo 'Array is not empty';
}

Using the array_key_exists Function

The array_key_exists() function checks if a specified key exists in an array. If the array is empty, no keys exist, so this can also determine emptiness. Example code:

$array = array();
if (!array_key_exists(0, $array)) {
  echo 'Array is empty';
} else {
  echo 'Array is not empty';
}

Note: Avoid using array_key_exists(0, $array) == false because the function returns a boolean false, not a string. Using negation is more accurate.

Limitations of isset Function

The isset() function checks whether a variable is declared and not null. However, it does not reliably determine if an array is empty, because missing keys in the array are considered unset. Therefore, it is not recommended for this purpose.

Summary

In PHP, the empty and count functions are the most commonly used and straightforward methods to check if an array is empty. Combining is_array with count helps avoid errors when the variable might not be an array. The array_key_exists function can also be used as an auxiliary check. Depending on the scenario, choose the most appropriate method to ensure code robustness and readability.

$array = array();
if (empty($array)) {
  echo 'Array is empty';
} else {
  foreach ($array as $value) {
    // ...
  }
}

Hopefully, this article helps you better understand and use array emptiness checks in PHP.