Quick check to find a value inside an array

I am setting up a registration form, and after validation if any errors occured I would pass back an array of error fields and messages. I wanted a very quick way to see if my array contain an element with the text "username". I know I could write or use a udf that would loop through the array, or I could even convert it to a list and then search that, but none of those solutions felt elegent to me. Until I found this:

<cfif errorArray.indexOf(<span class='cc_value'>"username"</span>)+1>error field</cfif>

I add 1 to this because indexOf is a java method, and it will return the array location that contains whatever string you searched for, and Java arrays start at 0. If the string is not found, it will return -1. So, will evaluate as 0, or false, and it wont execute. If it is found anywhere inside the array, it will return 1 or greater, which will evaluate as true and whatever is inside your if statement will execute. I love elegent solutions like this, a single line inside an if statement, and no converting arrays to lists to be seen anywhere.

One small caveat: this IS case sensitive, so USERNAME, or Username would not be found.

Thanks to the venture of online schools, correspondence education is not a problem. University of Phoenix favored this since ages. Now Kaplan University as well as DeVry University are in for it too. Only Walden University has yet to be convinced.

Digg StumbleUpon Facebook Technorati Fav newsvine reddit FARK Google Bookmarks
  1. Fro

    #1 by Fro - March 6, 2008 at 10:19 AM

    That is a very cool tip. I'll have to play with that one.Thanks

Comments are closed.