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?
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 will be removed.
With this it only returns the value which are not empty. See more in the docs example Example #2 array_filter() without callback
If you need to check if there are ANY elements in the array
if (!empty($tagcat) ) { //its $tagcat, not tagcat
echo 'array is NOT empty';
} else {
echo 'EMPTY!!!';
}
Also, if you need to empty the values before checking
foreach ($tagcat as $cat => $value) {
if (empty($value)) {
unset($tagcat[$cat]);
}
}
if (empty($tagcat)) {
//empty array
}
Hope it helps
EDIT: I see that you have edited your $tagcat var. So, validate with vardump($tagcat) your result.
if (empty($array)) {
// array is empty.
}
if you want remove empty elements try this:
foreach ($array as $key => $value) {
if (empty($value)) {
unset($array[$key]);
}
}