【问题标题】:Checking if associated array is empty or not [duplicate]检查关联数组是否为空[重复]
【发布时间】:2021-02-13 08:05:55
【问题描述】:

在下面的代码中,为什么我得到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"; 

【问题讨论】:

  • 数组有值,因此不为空
  • 对于您想要的那种支票,it should be this way
  • 感谢 nice_dev 这正是我想要的

标签: php


【解决方案1】:
<?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);

    

【讨论】:

    【解决方案2】:

    假设您要检查的数组将只包含一个数组或值(而不是矩阵数组),这将满足您的需求:

    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
    

    【讨论】:

      猜你喜欢
      • 2012-01-09
      • 2022-01-20
      • 2011-03-26
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多