简体   繁体   中英

How to check if all values in multidimensional array are empty

I have a form posting a multidimensional array to my PHP script, I need to know if all the values in the array are empty or not.

Here is my array:

$array[] = array('a'=>'',
                 'b'=>array('x'=>''),
                 'c'=>array('y'=>array('1'=>'')),
                 'd'=>'');

I tried using array_reduce(), but it's just returning an array:

echo array_reduce($array, "em");

function em($a,$b){
    return $a.$b;
}

Any ideas?

I noticed this has been hanging around for a while, this is a custom function that works quite well.

function emptyArray($array) {
  $empty = TRUE;
  if (is_array($array)) {
    foreach ($array as $value) {
      if (!emptyArray($value)) {
        $empty = FALSE;
      }
    }
  }
  elseif (!empty($array)) {
    $empty = FALSE;
  }
  return $empty;
}

if all items in the array is empty then the function will return true, but if one item in the array is not empty then the function will return false.

Usage:

if (emptyArray($ARRAYNAME)) {
  echo 'This array is empty';
}
else {
  echo 'This array is not empty';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM