Marco Marco - 4 months ago 13
PHP Question

How do i check if a declare array is empty?

I have an array called tagcat , like so

$tagcat = array();

....
while ( $stmt->fetch() ) {
$tagcat[$tagid] = array('tagname'=>$tagname, 'taghref'=>$taghref);
}


Using print_r($tagcat) i get the following result set

Array ( [] => Array ( [tagname] => [taghref] => ) )


Using var_dump($tagcat), i get

array(1) { [""]=> array(2) { ["tagname"]=> NULL ["taghref"]=> NULL } }


In php, i want to check if the array is empty. But when using the following conditions, it always finds something in the array, which is not true!

if ( isset($tagcat) ) {
echo 'array is NOT empty';
} else {
echo 'EMPTY!!!';
}

if ( !empty($tagcat) ) {
echo 'array is NOT empty';
} else {
echo 'EMPTY!!!';
}


How do i check if the array is empty?

Answer

Use array_filter

if(!array_filter($array)) {
  echo "Array is empty";
}

This was to check for the single array. For multi-dimensional array in your case. I think this should work:

$empty = 0;
foreach ($array as $val) {
  if(!array_filter($val)) {
    $empty = 1;
  }
}

if ($empty) {
  echo "Array is Empty";
}

If no callback is supplied, all entries of array equal to FALSE

With this it only returns the value which are not empty. See more in the docs example Example #2 array_filter() without callback

Comments