Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if an array is empty in PHP [duplicate]

Tags:

arrays

php

I have an array in PHP, which I have to check if it is empty.

    $length = count($array_new);
    if(empty($array_new)) 
        echo("Array is empty");
    else
        echo("Array is not empty");
    echo("\n");
    print_r($array_new);
    echo("Length of array is".$length);

The output is-

Array is not empty
Array
(
    [0] =>
    [1] =>
    [2] =>
    [3] =>
)
Length of array is 4

I know that the array is empty, then why does it show that the length of the array is 4? Can anyone tell me what is wrong here?

like image 624
SMG Avatar asked May 10 '26 12:05

SMG


1 Answers

Your array is not empty, you have assigned 4 keys without value.

empty($array_new)    // false
empty($array_new[0]) // true

To remove empty values from array use:

$filtered = array_filter($array_new, function ($var) {
    return !is_null($var);
});

Documentation:

  • empty()
  • array_filter()
like image 99
Grzegorz Gajda Avatar answered May 12 '26 04:05

Grzegorz Gajda