Skip to main content
Ben Nadel at DASH by Datadog 2018 (New York, NY) with: Gabriel Zeck and JD Courtoy
Ben Nadel at DASH by Datadog 2018 (New York, NY) with: Gabriel Zeck@GabeZeck ) and JD Courtoy@jd_courtoy )

Referencing String Characters Using Array-Notation In Lucee CFML

By on

Over the weekend, I was reading through the Learn Modern ColdFusion <CFML> in 100 Minutes book by Ortus Solutions when I came across their section on Character Extraction. In that section, they mention that - in Lucee CFML - you can access the characters of a String using Array-notation. Since I don't remember ever seeing this feature before, I wanted to quickly try it out for myself so as to try and burn the concept into my brain.

Like all ColdFusion arrays, lists, queries, etc, treating a String like an array of characters starts at index 1:

	value = "Jello";

	// A string can be accessed like an array of characters (1-based, of course).
	echo( value[ 1 ] & "-" );
	echo( value[ 2 ] & "-" );
	echo( value[ 3 ] & "-" );
	echo( value[ 4 ] & "-" );
	echo( value[ 5 ] & "-" );

	// Going out-of-bounds will throw an error; but, we can use our Elvis-operator to
	// provide a fall-back value for a null index.
	echo( value[ 6 ] ?: "!" );


As you can see, we are treating String value as a character Array. And, when we run this Lucee CFML code, we get the following output:


Interesting! To be honest, I don't have a lot of use-cases in which I have to iterate over the characters in a string in ColdFusion. But, it's good to know that this feature exists should the need arise.

ASIDE: I tried to use negative array indexing, like value[ -1 ], to grab the last character in the string. This does not work.

Also, attempting to use .map() on the String does not throw an error; but, it does not iterate over the string characters. It appears to perform a single iteration with the String value as the one iteration item.

Want to use code from this post? Check out the license.

Reader Comments


How about:

value[ Len(value) ]

I presume this works, for referencing the last character in word?
So, essentially, a string is an array of chars?



Yes, that's exactly right. But here's my emotional struggle: by the time you are going to start pulling in other methods like len(), I would probably just revert back to a simpler: value.right( 1 ). That's why I think this is "interesting"; but, I'm not sure how often I would actually use it.

Post A Comment — I'd Love To Hear From You!

NEW: Some basic markdown formatting is now supported: bold, italic, blockquotes, lists, fenced code-blocks. Read more about markdown syntax »
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.