How to Check Whether an Array Is Empty in PHP

Let’s see what PHP functions can you use to check whether the array is empty or not.

1. Check whether an array is empty or not with PHP empty () function

Example 1

<?php
$phone = array();
echo empty($phone) ? "Array is empty.": "Array is not empty.";
?>

The result for this will be Array is empty.

Example 2

<?php
 
$phone = array('00000','11111','22222');
echo empty($phone) ? "Array is empty.": "Array is not empty.";
?>

This will return to Array is not empty.

2. Use PHP count() function if you want to calculate the number of elements in an array.

If the array is empty, the function will return 0 ,otherwise it will return the number of the elements.

Example 1

<?php
$phone=array();
echo count($phone);
?>

The result for this will be 0. Thus the array is empty.

Example 2

<?php
$phone=array("00000","11111","22222", "33333");
echo count($phone);
?>

The above-mentioned example shows the number of the elements in the phone array. The result is 4.


Do you find this helpful?

Related articles