How to Check if an Array is Empty in PHP Code Snippet
This article explores how to check whether an array is empty in PHP. Here’s one way PHP checks empty array.
//An empty array
$arr_1 = [];
//Returns true if there are no elements in the array.
if(count($arr_1) === 0) {
echo "Array is empty";
} else {
echo "Array is not empty";
}
/*OUTPUT
Array is empty
*/
That’s just one way to check if array is empty in PHP. The article features more than that along with a case study. So, keep reading if you want to learn more.
Context: Empty Array PHP and Edge Cases
A robust code handles edge cases and error conditions without crashing or providing unexpected outcomes. A good developer will always make sure to use relevant techniques and utilities to write robust code. In a similar context, it is often necessary to check if an array is empty before processing or manipulating it.
Why though? There could be many reasons, but we have included a practical and exciting case study at the end of this article to give you some insights. Before that, we will see examples where PHP checks for empty array.
Scenario: API for Employees Data
Many applications fetch data from APIs. These APIs return data in the form of JSON. In PHP, you have to parse the JSON response into PHP arrays to work with the data. We have a built-in function json_decode for converting a JSON response into a PHP array.
It is nice to have a built-in function so that you do not have to reinvent the wheel. However, the JSON response itself could vary. That’s why to avoid errors and unexpected outcomes, PHP needs to check if an array is empty before further processing it.
Let’s say we have fetched a JSON containing employees data. The response is stored in a PHP variable, as shown.
//Employees data JSON fetched from an API
$employeeJSON = '[
{"Id":1,"Name": "Steve", "Job": "Full Stack Developer", "Skills":["MongoDB","Express.js","React.js","Node.js"]},
{"Id":2,"Name": "Bob", "Job": "Android Developer", "Skills":["Java","Kotlin","Flutter","Figma"]},
{"Id":3,"Name": "Jenny", "Job": "UI/UX Designer", "Skills":["Adobe XD","Adobe Illustrator","Figma"]}
]';
Background and Setup: Array of Employee Objects in PHP
In the next step, we would call json_decode to convert $employeeJSON into a PHP array. The output array looks like this.
Array
(
[0] => Array
(
[Id] => 1
[Name] => Steve
[Job] => Full Stack Developer
[Skills] => Array
(
[0] => MongoDB
[1] => Express.js
[2] => React.js
[3] => Node.js
)
)
[1] => Array
(
[Id] => 2
[Name] => Bob
[Job] => Android Developer
[Skills] => Array
(
[0] => Java
[1] => Kotlin
[2] => Flutter
[3] => Figma
)
)
[2] => Array
(
[Id] => 3
[Name] => Jenny
[Job] => UI/UX Designer
[Skills] => Array
(
[0] => Adobe XD
[1] => Adobe Illustrator
[2] => Figma
)
)
)
The output seems messy, right? We need to print data to the console in a more readable format. You’ll see how crucial it is to introduce checks at each step because you have no control over the API response.
Let’s see how PHP check for empty array and then deal with this array.
Option 1 – Check if an Array is Empty in PHP using IF/ELSE
A rudimentary technique for checking if an array is empty is through an IF/ELSE statement. I prefer this way because it simplifies the code, removes the overhead of calling a function, and raises a warning if an array doesn’t exist in the first place.
The IF statement returns false on encountering a falsey value. A falsey value is another interesting concept in PHP. However, we won’t go into it. For now, remember that an empty array is considered falsey, implying that the IF statement will not execute for an empty array. In the following example, PHP check for empty array.
//An empty array
$arr_1 = [];
//Returns false if an array is empty.
if($arr_1) {
echo "Array is not empty";
} else {
echo "Array is empty";
}
/*OUTPUT
Array is empty
*/
Straightforward, isn’t it? In the IF statement PHP if array is empty, and thus the ELSE statement executes for empty array. An equivalent code to this is the following.
//An empty array
$arr_1 = [];
//Returns true if an array is empty.
if(!$arr_1) {
echo "Array is empty";
} else {
echo "Array is not empty";
}
/*OUTPUT
Array is empty
*/
Here, the IF statement executes for an empty array, and PHP checks, if the array is not empty, (! negation), contrary to the first code. Although both are equivalent I prefer it this way because it seems more intuitive and direct.
Next, we will see how to check if an array is empty in PHP using the empty function.
Option 2 – Check Whether an Array is Empty in PHP using empty
PHP’s empty function returns true for an empty array. This function works for almost all data types and returns true for empty or falsey values. One concern is that it doesn’t raise a warning for undeclared variables but simply returns true. This peculiar behavior could be difficult to debug. The code below uses empty function.
//An empty array
$arr_1 = [];
//empty function returns true if an array is empty.
if(empty($aar_1)) {
echo "Array is empty or undeclared";
} else {
echo "Array is not empty";
}
/*OUTPUT
Array is empty or undeclared
*/
Quite intuitive. Because $arr_1 is empty, the empty function returns true, causing the IF statement to execute. Next, we will see isset function to check whether an array is empty in PHP.
Option 3 – PHP Check for Empty Array Using isset
The isset function in PHP returns true for declared variables with values other than null. It returns false for an empty array PHP. However, like the empty function, it doesn’t raise a warning or error for undeclared variables. Also, for beginners, the isset could be a bit difficult to comprehend.
We recommend you to read its official doc to understand it even better. Let’s put this function into action and check for empty PHP arrays.
//An empty array
$arr_1 = [];
//Returns true if an array is empty.
if(!isset($aar_1)) {
echo "Array is empty or undeclared";
} else {
echo "Array is not empty";
}
/*OUTPUT
Array is empty or undeclared
*/
The !isset evaluates to true for PHP empty array, thus the IF statement holds true.
Option 4 – Check PHP Empty Array with sizeof
PHP’s sizeof function returns the count of elements in an array. For empty arrays, the function will obviously return zero. This function will throw an error if the array is set to null. We can use this function in IF/ELSE statement to check if an array is empty in PHP. Let’s see how.
//An empty array
$arr_1 = [];
//Returns true if there are no elements in the array.
if(count($arr_1) === 0) {
echo "Array is empty";
} else {
echo "Array is not empty";
}
/*OUTPUT
Array is empty
*/
The idea is that if the count is zero, it means the array is empty. An alias to sizeof function is count, and it works pretty much the same way. You can check out its official doc.
Now, as you’ve seen multiple different ways to check if an array is empty in PHP, let’s move on to the case study that we’ve promised to include in the article.
Check PHP Empty Arrays in Employees Data
Here’s the example that checks the employees’ array and checks for empty array values.
/Response has been parsed.
$parsed_response = json_decode($employeesJSON, true);
//If JSON converts the if statement will execute.
if(!empty($parsed_response))
{
//Loop the array for each employee data.
foreach($parsed_response as $employee)
{
//Check if the name attribute is set
isset($employee["Name"]) ? $name = $employee["Name"] : $name = "N/A";
isset($employee["Job"]) ? $job = $employee["Job"] : $job = "N/A";
//Print to console.
echo "Name: ".$name."\nJob: ".$job;
echo "\nSkills: [";
//Checks if the skills array is not empty.
if(!empty($employee["Skills"]))
{
foreach($employee["Skills"] as $skill)
{
echo $skill." ";
}
}
echo "]\n===================================\n";
}
}
//If the conversion fails then the $parsed_response will be empty
else
{
echo "JSON conversion has failed.";
}
You can see we have introduced multiple checks in the code. A code without these won’t be robust enough to accommodate edge cases like failed JSON to array conversion. That’s why we always need to check if an array is empty to avoid errors and crashes.
By the way, we get the following output from this code.
Name: Steve
Job: Full Stack Developer
Skills: [MongoDB Express.js React.js Node.js ]
===================================
Name: Bob
Job: Android Developer
Skills: [Java Kotlin Flutter Figma ]
===================================
Name: Jenny
Job: UI/UX Designer
Skills: [Adobe XD Adobe Illustrator Figma ]
===================================
Quite better than just printing out an array. That’s it, time for wrapping this up!
Conclusion
Wrap Up
This article explores how to check if an array is empty in PHP. It starts with a brief context and a case study. Following that, it features four different options where PHP checks for empty arrays. Lastly, the article includes a solution to the case study problem.
Hopefully, you’ve liked the article. Stay tuned for more content at FuelingPHP.
Classes and Functions Mentioned
json_decode: (PHP 5.2+, 7, 8) This function is quite handy in transforming JSON to a PHP array or object. It is commonly used in various scenarios where transformation is necessary. Besides, it is a core function, and based on the extensive use over time it seems depreciation is unlikely in the near or distant future.
isset: (PHP 4, 5, 7, 8) This function is native to PHP and checks for undeclared variables. It has been available from an early PHP version and remains a part of it. Its depreciation seems unlikely in the future.
empty: (PHP 4, 5, 7, 8) A core PHP function that checks if a variable is empty. Being a part of PHP from version 4, it remains stable and likely would remain so in the future.
sizeof: (PHP 4, 5, 7, 8) An array function that returns the length of an array in PHP. It has been available in the latest version too and given its use its depreciation seems unlikely.
Want to explore further about PHP arrays?
We have many fun articles related to PHP arrays. You can explore these to learn more about arrays in PHP.