Recently, I need to check for an empty value in an array. While empty() is good for checking a specific value it does not allow the checking of a whole array. I didn’t want to do multiple if statements/empty checks and also empty was not always accurate, i.e. if a variable has a value of 0 (zero) then empty considers it empty – but for my purposes this was not empty. How to solve this problem?
Well, I decide to create my own function. It’s a fairly simple one – returns FALSE if no empty array item is detected, otherwise TRUE if one is. For my purposes, I did not need to know in the check which one specifically is empty as the error message for individual items would always be reported by another function (it was for a HTML form, so the error is displayed next to each field based upon a conditional check for that specific field).
Anyway, enough of my babbling and on to the code, which I hope someone else also finds useful:
function checkforemptyval($array) {
$is_empty = 0;
foreach($array as $key => $item) {
if(is_numeric($item)) {
} elseif(empty($item)){
$is_empty++;
}
}
if($is_empty > 0)
return TRUE;
else
return FALSE;
}
It is simple to use, here is a quick example:
if(!checkforemptyval($array)) {
#do something as the test was FALSE, i.e. no empty value found
save_form($array);
} else {
#do something else as there was an empty value, i.e. TRUE was reported.
edit_form($array);
}
Perhaps this could be done better, but I just wanted to put together a quick function. If you have any improvement suggestions then leave a comment (or if you found the code useful let me know also!).
Related posts:
Here is a function, which returns a array with non-empty elements/items :
function removeEmpty($rawArray)
{
$arrayindex=0;
$cleanArray=Array();
foreach($rawArray as $val)
{
if(!empty($val))
{
$cleanArray[$arrayindex]=$val;
$arrayindex++;
}
}
return($cleanArray);
}
checkforemptyval($array) is really clever. I have been doing insanely long,
if (!$_POST['email'] | !$_POST['confirm_email'] | !$_POST['password'] | !$_POST['confirm_password'] |
!$_POST['firstname'] | !$_POST['lastname']| !$_POST['address'] | !$_POST['city'] | !$_POST['state'] |
!$_POST['zip']| !$_POST['phone'])
statements. Until now. thanks Paul
Superb… I’m still new to PHP and have been scratching my head on this one for a while. Thanks a lot!!