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!).

Share and Enjoy:
  • Twitter
  • StumbleUpon
  • Facebook
  • del.icio.us
  • Mixx
  • Propeller
  • BlinkList
  • Simpy

Related posts:

  1. Getting PHP5 And Postgresql To Work Together In Windows
  2. A PHP Google Adsense Referrals Script Version 2 Fixes
  3. A PHP Google Adsense Referrals Script Version 2
  4. Part 1: Preventing Image Hotlinking Web Scrapers And Referral Spam
  5. PHP Adsense-Referrals Script Version 2.1