How to Check Whether an Array Is Empty using PHP
Posted By
Bajarangi soft ,
Posted On 03-12-2020
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:
1.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:
Example:
<?php
//declare an array and initialize it
$non_empty_array=array('URL'=>'https://wwww.google.com');
//declare an empty array
$empty_array=array();
//condition for check whether array is empty or not
if(!empty($non_empty_array))
echo "given array is not empty <br>";
if(empty($empty_array))
echo "given array is empty";
?>
2.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
$empty_array=array();
//function to count array element and use condition
if(count($empty_array)==0)
echo"array is empty";
else
echo"array is non-empty";
?>
3.Using Sizeof() unction: 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 not
if(sizeof($empty_array)==0)
echo "empty array";
else
echo "non-empty array";
?>