Mimic PHP's empty() function in ColdFusion

Almost anyone who has ever heard me talk about about ColdFusion has undoubtedly heard me say it sucks. It's slowly improving (CFMX 8 finally supports JavaScript-style arithmetic operators), but it has a ways to go. For instance it doesn't support ternary operators.

Normal if-else assignment loop

if( $today_is_saturday ) {
  $weekend = true;
} else {
  $weekend = false;
}

Assignment using a ternary operator

$weekend = $today_is_saturday ? true : false;

But I digress. There is also no easy way to tell if a variable is empty, unlike PHP's empty() construct which will return true for any of the following:

  • "" (an empty string)
  • 0 (0 as an integer)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

In ColdFusion you need a User Defined Function (UDF) to accomplish this, and I've written one that mimics this as closely as possible. CF doesn't have a null data type, and if it receives one it'll convert it to an empty string.

The Code

Copy and paste this somewhere inside your code and call it using empty(varName). The varName variable must be defined.

<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>

 

Tags: , , ,

Leave a Reply