7

Check if an array is empty in PHP

 1 year ago
source link: https://thispointer.com/check-if-an-array-is-empty-in-php/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

This tutorial will discuss about unique ways to check if an array is empty or not in php.

Table Of Contents

Method 1: Using empty() function

The empty() function in PHP accepts a variable as an argument, and returns true if variable is empty i.e. either variable does not exists or it evaluates to false.

We can pass an array object in it, to check if an array is empty or not. If it returns true, then it means array is empty, otherwise it is not empty.

Let’s see the complete example,

Advertisements

<?php
// create an empty array
$arr = array();
// Check if array is empty
if (empty($arr)) {
echo "Yes, the array is empty";
} else {
echo "No, the array is not empty";
?>
<?php
// create an empty array
$arr = array();

// Check if array is empty
if (empty($arr)) {
    echo "Yes, the array is empty";
} else {
    echo "No, the array is not empty";
}
?>

Output

Yes, the array is empty
Yes, the array is empty

Method 2: Using count() function

The count() function in PHP accepts an array as an argument, and returns the number of elements in the array. If it returns 0, then it means that the array is empty, otherwise array is not empty.

Let’s see the complete example,

<?php
// create an empty array
$arr = array();
// Check if count of elements in array is 0
// Check if array is empty
if (count($arr) == 0) {
echo "Yes, the array is empty";
} else {
echo "No, the array is not empty";
?>
<?php
// create an empty array
$arr = array();

// Check if count of elements in array is 0
// Check if array is empty
if (count($arr) == 0) {
    echo "Yes, the array is empty";
} else {
    echo "No, the array is not empty";
}
?>

Output

Yes, the array is empty
Yes, the array is empty

Summary

We learned about two ways to check if an array is empty or not in PHP


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK