OneBite.Dev - Coding blog in a bite size

Check If Array Is Empty In PHP

Code snippet for how to Check If Array Is Empty In PHP with sample and detail explanation

Working with arrays is a fundamental facet of PHP programming, and different situations may necessitate checking if an array is empty. This article covers a simple way to check if an array is empty in PHP through a straightforward code snippet and a step-by-step explanation of the code.

Code snippet to Check If Array Is Empty In PHP

Here is a sample PHP code snippet to check if an array is empty:

<?php
    $array = array();
    if (empty($array)) {
        echo "The array is empty.";
    } else {
        echo "The array is not empty.";
    }
?>

Code Explanation for checking if an array is empty in PHP

The first line of the PHP code sets up an empty array variable using the array() function:

$array = array();

This line effectively declares an array, $array, but leaves it empty at this point.

The if statement checks if this $array is empty:

if (empty($array)) {

The if statement works in conjunction with an inbuilt PHP function, empty(), to check for the condition. The empty() function, quite conveniently, returns a boolean TRUE if the tested variable, in this case $array, is empty and FALSE if it is not.

If the condition in the if statement is TRUE, which means that the array is indeed empty, the subsequent block of code is executed informing that the array is empty:

echo "The array is empty.";

If it returns FALSE, meaning the array is not empty, the code in the else clause or block is executed, stating that the array is not empty:

else {
    echo "The array is not empty.";
}

Remember that the empty() PHP function not only checks if the array is empty but also returns a boolean check for pre-existing variables that contain no value or simply fail the condition of being set, thereby accounting for NULL and FALSE effects. Through this simple tutorial, you should be able to check if an array is empty in PHP successfully.

php