0

In the below code, why am I getting Given Array is not empty while all keys has no values? How can I check if an associated array like this is empty or not?

<?PHP
$args = array(
               "A" => [], 
               "B" => [], 
               "C" => [], 
               "D" => [], 
               "E" => [], 
               "F" => [], 
               "G" => [], 
               "H" => []
              );

if(!empty($args)) 
    echo "Given Array is not empty"; 
  
if(empty($args)) 
    echo "Given Array is empty"; 
halfer
  • 19,824
  • 17
  • 99
  • 186
Behseini
  • 6,066
  • 23
  • 78
  • 125

2 Answers2

0
<?php

$args1 = array(
               "A" => [], 
               "B" => [], 
               "C" => [], 
               "D" => [], 
               "E" => [], 
               "F" => [], 
               "G" => [], 
               "H" => []
              );
              
$args2 = array("" => [], "" => []);

function assocArrayIsEmpty($arr){
    $empty = true;
    foreach($arr as $key => $value){
        if(isset($key) && !empty($key) || isset($value) && !empty($value)){
            $empty = false;
        }
    }
    return "Given Array is ".($empty ? "empty":"not empty");
}

echo assocArrayIsEmpty($args1);
echo "\r\n";
echo assocArrayIsEmpty($args2);

    
symlink
  • 11,984
  • 7
  • 29
  • 50
0

Assuming the array you want to check will only contain an array or value (and not a matrix array), this will do what you are wanting:

function checkArrayEmpty($args) {
    $ret = true;

    $values = array_values($args);
    foreach ( $values as $value ) {
        if ( !empty($value) ) {
            $ret = false;
        }
    }

    return $ret;
}

$args = array("A" => ['test']);
$is_array_empty = checkArrayEmpty($args); 
var_dump($is_array_empty);// false, not empty

$args = array("A" => 'test');
$is_array_empty = checkArrayEmpty($args); 
var_dump($is_array_empty);// false, not empty

$args = array("A" => [], "B" => []);
$is_array_empty = checkArrayEmpty($args); 
var_dump($is_array_empty);// true, all keys contain nothing or empty array