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.
Table of Contents
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
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
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
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
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
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
Interactive Example
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!