Open In App

How to check whether an array is empty using PHP?

Last Updated : 04 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn how can we check whether an array is empty using PHP. There are various methods and functions available in PHP to check whether the defined or given array is empty or not.

These are the following methods by using these we can solve our problem:

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.

Example: In this example, we are using the empty() function.

PHP




<?php // Declare an array and initialize it $non_empty_array = array('URL' => 'https://www.geeksforgeeks.org/');
// Declare an empty array
$empty_array = array();
 
// Condition to check 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";
?>


Output

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.

Example: In this example, we are using the count() function.

PHP




<?php
 
// Declare an empty array
$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";
?>


Output

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: In this example, we are using the sizeof() function.

PHP




<?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";
?>


Output

Empty Array 

Using not (!) operator

In this method, we are checking whether the given array is empty or not by using not operator.

Example: In this example, we are using the not operator.

PHP




<?php
 
// Declare an empty array
$empty_array = array();
 
// Use array index to check
// array is empty or not
if( ! $empty_array)
    echo "Empty Array";
else
    echo "Non-Empty Array";
?>


Output

Empty Array 

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads