Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to check whether an array is empty using PHP?
In PHP, there are several methods to check whether an array is empty. The most common approaches include using the empty() function and the count() function.
Using empty() Function
The empty() function returns true if the array has no elements −
<?php
$arr = array("p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110");
if (empty($arr)) {
echo "Empty Array...";
} else {
echo "Array isn't empty...";
}
?>
Array isn't empty...
Example with Empty Array
<?php
$arr = array();
if (empty($arr)) {
echo "Empty Array...";
} else {
echo "Array isn't empty...";
}
?>
Empty Array...
Using count() Function
The count() function returns the number of elements in an array. An empty array has a count of 0 −
<?php
$arr = array("p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110");
if (count($arr) == 0) {
echo "Empty Array...";
} else {
echo "Array isn't empty...";
}
?>
Array isn't empty...
Comparison
| Method | Function | Performance | Use Case |
|---|---|---|---|
empty() |
Checks if variable is empty | Faster | Simple empty check |
count() == 0 |
Counts array elements | Slightly slower | When you need the count value |
Conclusion
Both empty() and count() methods effectively check for empty arrays. Use empty() for simple checks as it's more efficient, and count() when you need the actual array size.
Advertisements
