Home » PHP » PHP Examples

Check if an array is empty or not in PHP

Here, we are going to learn how to check whether a given array in an empty array or not in PHP?
Submitted by Bhanu Sharma, on September 19, 2019

Given an array and we have to check if array is an empty or not using PHP.

To check whether an array is empty or not, we can use a built-in function empty(), in other cases where we want to check if a given variable is empty or not, it can also be used. It returns a Boolean response based on the condition that if the given variable contains a non-empty, non-zero value then it returns "false" otherwise, it returns "true".

Syntax:

    empty ($var);
    empty ($array);

PHP code:

<?php
    // array declaration
    $array1 = array('hello', 'world');
    $array2 = array();
    
    //checking whether arrays are empty or not
    if (empty($array1)) {
        echo "array1 is empty\n";
    } else {
        echo "array1 is not empty\n";
    }
    
    if (empty($array2)) {
        echo "array2 is empty\n";
    } else {
        echo "array2 is not empty\n";
    }
?>

Output

array1 is not empty
array2 is empty





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.