4

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?

littleRoom
  • 81
  • 2
  • 5
  • Perhaps you can check this thread.. http://stackoverflow.com/questions/17506199/how-to-check-if-a-multi-dimensional-array-only-contains-empty-values – Hendyanto Nov 15 '13 at 02:17
  • I did see that post before posting myself, but those answers seem to only work on a single level of the multidimensional array. The array in my example has varying depths. – littleRoom Nov 16 '13 at 01:36

1 Answers1

5

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';
}
jafacakes2011
  • 188
  • 2
  • 6