Different ways of checking if an array is empty or not in PHP


Using the ‘sizeof’ function

Let us see an example −

Example

 Live Demo

<?php
$empty_arr = array();
if( sizeof($empty_arr) == 0 )
   echo "The array is empty!";
else
   echo "The array is non-empty.";
?>

Output

The array is empty!

An array can be checked to see if it is empty or not in multiple ways. One method is to use the ‘sizeof’ function that sees if the array is empty. If yes, the size would be 0, thereby confirming the array being empty.

Using the ‘empty’ function

Example

 Live Demo

<?php
$my_arr = array('URL' => 'https://www.medium.com/');
$empty_arr = array();
if(!empty($my_arr))
   echo "The array is non-empty <br>";
if(empty($empty_arr))
   echo "The array is empty!";
?>

Output

The array is non-empty
The array is empty!

Another method to check if an array is empty or not is to use the ‘empty’ function, that checks to see the contents of the array, and if nothing is present, says it is empty.

Updated on: 02-Jul-2020

307 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements