php - Checking if associated array is empty or not
Solution:
<?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);
Answer
Solution:
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
Source