How to check whether an array is empty using php
By Ved Prakash N |
Sep 22, 2023 |
PHP
How to check whether an array is empty using php
In this post, you will be learning how to find if an array is empty or not in PHP. 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:
bool empty($var)
Example:
<?php
// Declare an array and initialize it
$myArray = array(
'Website' => 'Funda of Web IT',
'URL' => 'www.fundaofwebit.com'
);
// Condition to check array is empty or not
if(!empty($myArray)){
echo "Given Array is not empty <br>";
}
// Declare an empty array
$myEmptyArray = array();
if(empty($myEmptyArray)){
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
// Declare an empty array
$empty_array = array();
// Function to count array
if(count($empty_array) == 0){
echo "Array is empty";
}else{
echo "Array is non- empty";
}
?>
3. 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
$myArray = array();
// Use array index to check array is empty or not
if( sizeof($myArray) == 0 ){
echo "Empty Array";
} else {
echo "Non-Empty Array";
}
?>
I hope this helped you. Thanks for reading.