How to check whether an array is empty using PHP?
An empty array can sometimes cause software crash or unexpected outputs. To avoid this, it is better to check whether an array is empty or not beforehand. There are various methods and functions available in PHP to check whether the defined or given array is an empty or not. Some of them are given below:
- Using empty() Function: This function determines whether a given variable is empty. This function does not return a warning if a variable does not exist.
Syntax:
bool empty( $var )
Example:
<?php// Declare an array and initialize it// Declare an empty array$empty_array=array();// Condition to check array is empty or notif(!empty($non_empty_array))echo"Given Array is not empty <br>";if(empty($empty_array))echo"Given Array is empty";?>chevron_rightfilter_noneOutput:Given Array is not empty
Given Array is empty - Using count Function: This function counts all the elements in an array. If number of elements in array is zero, then it will display empty array.
Syntax:
int count( $array_or_countable )
Example:
<?php// Declare an empty array$empty_array=array();// Function to count array// element and use conditionif(count($empty_array) == 0)echo"Array is empty";elseecho"Array is non- empty";?>chevron_rightfilter_noneOutput:Array is empty
- Using sizeof() function: This method check the size of array. If the size of array is zero then array is empty otherwise array is not empty.
Example:
<?php// Declare an empty array$empty_array=array();// Use array index to check// array is empty or notif( sizeof($empty_array) == 0 )echo"Empty Array";elseecho"Non-Empty Array";?>chevron_rightfilter_noneOutput:Empty Array
Recommended Posts:
- Check if an array is empty or not in JavaScript
- Why to check both isset() and !empty() function in PHP ?
- How to check an object is empty using JavaScript?
- How to check an HTML element is empty using jQuery ?
- How to check empty/undefined/null string in JavaScript?
- Best way to initialize empty array in PHP
- Python - Initialize empty array of given length
- Program to remove empty array elements in PHP
- unordered_map empty in C++ STL
- PHP | empty() Function
- multimap empty() function in C++ STL
- unordered_set empty() function in C++ STL
- How to check an array is multidimensional or not in PHP ?
- Checking if structure is empty or not in Golang
- How to check an array is associative or sequential in PHP?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

