检查2D数组中值是否为空的最简单方法是什么?


What's the simplest way to check that values aren't empty in 2D array?

例如,我有一个这样的数组:

array(4) ("a" => string(0))" "b" => string(0)" "c" => string(0)" "d" => string(0)" ")

给定的值不能为空。

现在,我用这个:

if (!empty($_POST['x']['a']) && !empty($_POST['x']['b']) && !empty($_POST['x']['c']) && !empty($_POST['x']['d']))

…这在可读性方面很糟糕。

count(array_filter($_POST['x'])) === 4

说明:Empty()是布尔变量的反面,array_filter删除所有等于false的元素(即!empty()),并且该计数必须符合4个元素的期望。

如果元素的数量是由提交的元素总数定义的(无论是否为空),则使用count()代替幻数:

if (count(array_filter($_POST['x'])) === count($_POST['x']))
{
    echo 'No empty elements in $_POST["x"]!';
}

检查过array_reduce函数了吗?

function all_empty($v,$w){
   $v .= $w;
   return $v;
}
if(array_reduce($_POST['x'],'all_empty','')==''){

我还没有测试过,但是你可以试试

编辑:(回复评论)

你可以将"不酷"的逻辑封装在一个函数中,然后用一行代码调用它:

if ( check_for_empty_values( $_POST ) ) { // Do something }

封装的检查逻辑:

function check_for_empty_values( $data ) {
    $valid = true;
    foreach ( $data as $element ) {
        if ( is_array( $element) ) {
            foreach ( $element as $subelement ) {
                if ( empty( $subelement ) ) {
                    $valid = false;
                }
            }
        }
    }
    return $valid;
}
for($_POST as $key => $value) {
    if( !empty($value) ) {
      // Do stuff.    
    }
}