cfg
7/27/2011 - 7:25 PM

Mimic PHP's empty() function in ColdFusion

Mimic PHP's empty() function in ColdFusion

<!---
See: http://coreygilmore.com/blog/2008/05/01/mimic-phps-empty-function-in-coldfusion/
--->
<cfscript>
function empty(val) {
  /**
   * Return TRUE if one of the following conditions
   * for a defined variable is met:
   *  - A *trimmed* string is empty
   *  - An array or struct is empty
   *  - A query has a recordcount of 0
   *  - A bool is false
   *  - A number is 0
   *
   * For all other values including IsDate(testVar) it returns false.
   *
   * Similar to the php empty() function, www.php.net/empty
   *
   * @param val Variable to test. (Required)
   * @return Returns a boolean.
   * @author Corey Gilmore (http://coreygilmore.com/)
   *
   */
 
  if( IsSimpleValue(val) ) {
    if( IsDate(val) ) {
      return false; // no validation here
    } else if( IsNumeric(val) ) {
      return YesNoFormat(val EQ 0);
    } else if( IsBoolean(val) ) {
      return NOT YesNoFormat(val);
    } else {
      // assume string
      return NOT YesNoFormat( Len(Trim(val)) );
    }
  } else {
    if( IsArray(val) ) {
      return NOT YesNoFormat( ArrayLen(val) );
    } else if( IsStruct(val) ) {
      return StructIsEmpty(val);
    } else if( IsQuery(val) ) {
      return NOT val.recordcount;
    }
  }
 
  return false;
}
</cfscript>