I coulda sworn I had blogged this earlier but it didn't show up on my search. This just came up in a meeting at work so I thought I'd share. ColdFusion 8 added the arrayIsDefined function. As you can probably guess it let's you check to see if an array has a value at a certain position. However, it had one pretty silly drawback. If your array was had a size of 10 and you checked position 11, you would get an error. Therefore to really check to see if a certain array position existed, you had to use this:
<!--- assume array is called arr and N is the position you want to check --->
<cfif arrayLen(arr) gte n and arrayIsDefined(arr, n)>
ColdFusion 9 though fixes this. So your code can just be:
<!--- assume array is called arr and N is the position you want to check --->
<cfif arrayIsDefined(arr, n)>
Oddly, the docs for arrayIsDefined still insist that you must stay within the bounds of the array. I'm filing a comment now.
Archived Comments
It would be sweet if this functionality worked with isDefined()... as in isDefined( arr[ n ] ).
Awe, com'on now Ben it's like 5 characters more :) I can't wait until ColdFusion has the feature
DoAllTheWorkForMe("ProjectName"); Then your application is done. Can't wait,... can't wait.
@Jody: If we make things too easy, the PHPers and Ruby dev's will commit suicide out of jealousy.
@Jody,
Ha ha... but isNull() just *looks* cooler :)
You aren't cool unless you combine isNull with the trenary operator and DE at the same time.
Ha ha ha :) Might want to throw an IncrementValue() in there for good measure.
I smell a Friday contest.
Ha ha, sweeeet :)
What would really be nice is if there were one function that could check if an element in an array of structs (or other complex objects) exists.
E.g. isDefined("my_array[n].element_foo")
While it doesn't return a boolean, you can do that with structGet. It will attempt to find the variable based on a complex string path. It will even create stuff. So given your example, if my_array existed, but item N did not, and element_foo did not, it would make it.
structGet - the function no one uses! ;)
Hi. Call me crazy, but my CF 9 implementation still seems to include the CF 8 style bug. I had to revert back to using arraylen GTE... Anyone else seen this?
Um, ok, I'm confused now too. I see the same. I swear this worked. Can anyone else check?
Turns out I was on crack. I have no idea _why_ I put this blog post up when it really didn't work. I apologize folks.
The good news is that I can confirm it is fixed for CF901. You didn't hear that from me though.
Good lord, thank you! What a pain....