How to check if a multi-dimensional array only contains empty values?

这一生的挚爱 提交于 2019-12-03 04:03:52

If you wanted to check to see if all of the values where populated you can use

 if(call_user_func_array("isset", $array['foo']['bar']))

For what you want to do though you could use array reduce with a closure

 if(array_reduce($array, function(&$res, $a){if ($a) $res = true;}))

Note this will only work in php 5.3+

$array['foo']['bar'] isn't empty because it's actually array(1=>'',2=>'',3=>'',4=>'').

You would need to do a foreach loop on it to check if it is indeed all empty.

$arr_empty = true;
foreach ($array['foo']['bar'] as $arr) {
    if (!empty($arr)) {
        $arr_empty = false;
    }
}
//$arr_empty is now true or false based on $array['foo']['bar']

A short alternative would be:

if (empty(implode($array['foo']['bar']))) {
  // is empty
}

Note that some single values may be considered as empty. See empty().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!