14 June, 2010

Find if multi-dimensional array is empty

Checking for emptinessin quite simple using php. Following function can be used to check if a multidimensional array is empty or not.
The code loops through all the values in multi-dimensional array to check for empty values.

$food = array(
'fruits' => array('', '', ''),
'veggie' => array('', '', ''),
"test" => ""
);
//set the empty count to 0
$countEmpty = 0;
//set number of keys count to 0
$countKey = 0;
foreach($food as $key => $val) {
if(is_array($val)) {
//loop through each values inside
foreach($val as $key1 => $val1) {
$val = trim($val);
if(empty($val1)) {
//empty value-- increment the empty value count
$countEmpty++;
}
//increment the key count
$countKey++;
}
}
else {
$countKey++;
$val = trim($val);
if(empty($val)) {
$countEmpty++;
}
}
}
if($countKey == $countEmpty) {
echo "Array is empty..!";
}
else {
echo "Array contains".($countKey - $countEmpty)." value(s)";
}
echo "
";
echo "Keys:".$countKey."
";
echo "Empty:".$countEmpty;
?>

No comments: