在下面的代码中,为什么在所有键都没有值的情况下得到Given Array is not empty
?如何检查这样的关联数组是否为空?
<?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";
答案 0 :(得分: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);
答案 1 :(得分:0)
假设您要检查的数组仅包含一个数组或值(而不是一个矩阵数组),这将满足您的要求:
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