What if there is an empty array in the code? The empty array can be the cause of unexpected outputs and software crashes. Therefore, it is recommended to check if any of the arrays are empty or not beforehand.Â
In PHP, there are built-in methods for finding whether an array is empty or not. It is the developer’s choice for what function he/she will opt for checking the array. It is all about their requirements and preferences.
In this article, we will learn how to check if the array is empty or not using PHP. There will be example code snippets for different methods along with the output for proper understanding.
Table of Contents
1. empty( )
empty( ) is an built-in function of PHP. The empty( ) function is used to check if the provided variable is empty or not. Arrays are also included in the variables. The syntax is given by:
empty ( $variable/ $array );
It has one mandatory parameter. This method returns a Boolean value and does not create any warning if there is no variable found.
<?php
$myarray1 = array('Welcome to Code Leaks');
$myarray2 = array();
if (empty($myarray1)) {
echo "This array is EMPTY.\n";
}
else {
echo "This array is NOT EMPTY.\n";
}
if (empty($myarray2)) {
echo "This array is EMPTY.\n";
}
else {
echo "This array is NOT EMPTY.\n";
}
?>
Output:

2. sizeof( )
It is an inbuilt PHP method. sizeof( ) calculates the size of array. If the array size is zero, then it is said to be empty. If their size of the array returns a number, it means the array is not empty. The syntax rule is :
sizeof( $array, $mode )
It has two parameters; the array is a mandatory parameter. Mode is specified for recursive size, and it is optional.
<?php
$EmptyArray = array();
$size = sizeof($EmptyArray);
echo "This array has size $size. \n";
if(sizeof($EmptyArray) == 0)
echo "This array is EMPTY.";
?>
Output:

3. NOT Operator
The NOT(!) operator is also a good option to find whether an array is empty or not. The following code block is an example of the NOT operator.
<?php
$myArray1= array("1", "2");
$myArray2= array();
if (!$myArray1) {
echo "This array is EMPTY.\n";
}
else {
echo "This array is NOT EMPTY.\n";
}
if (!$myArray2) {
echo "This array is EMPTY.\n";
}
else {
echo "This array is NOT EMPTY.\n";
}
?>
Output:

4. count( )
The count function is also a PHP inbuilt function. It counts the elements in an array. It works like the sizeof( ) function. The array will be displayed empty if there is no element with the count( ) function.
The syntax is:
count( $array, $mode )
Count( ) function accepts two parameters, mode is an optional parameter.
<?php
$myArray = array();
$size = count($myArray);
echo "This array has size $size. \n";
if(count($myArray) == 0)
echo "This array is EMPTY.";
?>
Output:

Conclusion
In this article, we have discussed 4 different techniques of finding an empty array in PHP. I hope the examples were quite helpful in understanding the concept.