Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Maureen O'Gara, Nancy Y. Nee, Tad Anderson, Daniel Kaar

Related Topics: ColdFusion

ColdFusion: Article

Testing Existence in Arrays

Testing Existence in Arrays

Have you ever wanted to test if a given array element exists? Or when dealing with arrays of structures, if a given key exists?

Both are challenging if you try to use IsDefined(). This article addresses why IsDefined() fails in both cases when working with arrays.

Part 1: Testing for Existence with an Array
The first problem arises in the following example: you have an array with four items, but the two in the middle don't have any value (not an empty string, but no array elements at two of the array positions). Consider the following code:

<CFSET ACart = ArrayNew(1)>
<CFSET ACart[1] ="Nokia 8150 phone">
<CFSET ACart[4] ="Carrying case">

<CFOUTPUT>
<CFLOOP FROM="1" TO="#arraylen(ACart)#" INDEX="i">
Item: #ACart[i]# <br>
</CFLOOP>
</CFOUTPUT>

Notice there are only two elements in the array at positions 1 and 4. (Let's not get hung up on why someone would do this. I've hard-coded it this way, but there are a number of programmatic situations in which you'd get an array with elements missing.) An example of this is basing the array location on the value of the table's numeric primary keys when mapping query results to an array.

The point is you may end up inserting data into some array elements, but not others. You're intentionally not adding new elements to the end of the array, because array elements are representing some other data structure. If there are no values at a given point in the original, you don't want them in the array, either.

The main problem is when you loop through the array. During the second iteration, where there's no second array element, you'll get an error trying to refer to ACart[2]:

The element at position 2 in dimension 1 of object "ACart" cannot be found. The object has elements in positions 1 through 4. Please, modify the index expression.

The question is: How do you test if a given element exists before trying to use it?

Testing Existence with IsDefined()
You may try to wrap the use of the ACart array (inside the loop) in a test for IsDefined() as in:

<CFIF IsDefined("ACart[i]")>
Item: #ACart[i]# <br>
<.CFIF>
That will fail, though, saying:

Parameter 1 of function IsDefined which is now "ACart[i]" must be a syntactically valid variable name

This can be frustrating because it seems a valid variable. You can output the same variable in the loop, right? If the array element being tested had a value?

IsDefined() Expects a String
Those with more experience might point out that the problem is that the value of i is not being reflected as a dynamically changing number, since the variable name is in quotes (the IsDefined() function expects a string after all). That's not the solution either. Changing it to:

<CFIF IsDefined("ACart["&i&"]")>
would solve the problem if that were the issue. But this approach still fails, with:

Parameter 1 of function IsDefined which is now "ACart[1]" must be a syntactically valid variable name

This is frustrating because ACart[1] is a valid variable name! Moreover, there is indeed data in that array element. The simple answer is you can't test for the existence of an array element with IsDefined. But how then do you test for it?

Testing Existence with IsArray()
You may be tempted to look into the IsArray() function and one of its less-known features to test for the existence of a particular dimension within the array, using:

IsArray(ACart,i)

That's incorrect thinking. This tests whether there's an array of the given dimension. Our array above is a one-dimension array. It has two elements, but it's still a one-dimension array. (See the Allaire docs or the Allaire Advanced ColdFusion class for more on multidimensional arrays.)

If you're hoping it returns false when it gets to the value of I=2 in the loop above, you'd be right. But that's because there aren't two dimensions in the array. The more critical point is that IsArray(ACart,4) would also be false. It's not testing if an element exists at the given position in the array. It's testing if it's a four-dimension array. It's not, and it would be inappropriate to make this a multidimensional array to force this IsArray() function to work for us. It's just not an appropriate solution.

Drop Back and Punt: CFTRY/CFCATCH
We need to know if a given element in the array exists, but there seems to be no conventional way to test for that. There's a kind of brute force way around it. You could put the code that's trying to use the array elements inside a CFTRY and cause it to ignore the error that arises, as in:

<CFLOOP FROM="1" TO="#arraylen(ACart)#" INDEX="i">
<CFTRY>
Item: #ACart[i]# <br>
<CFCATCH>
</CFCATCH>
</CFTRY>
</CFLOOP>

This states that if the attempt to use any given array element fails, the error handler should catch it and ignore the error (we give it nothing to do in the CFCATCH, so it passes out of the CFTRY and on to the next iteration of the loop).

This way you don't get any errors, but it doesn't look obvious to a programmer who has to maintain your code (a comment would definitely be warranted!).

CFPARAM: A Possible Solution
We mentioned earlier that prepopulating the array could solve the problem by ensuring there was always a value in each array element. That seems kludgy, especially doing some sort of loop to put a default value in each element and then testing for that default during each iteration through the array. Indeed, there are times when that wouldn't be appropriate anyway, since it may be significant that there's no value in particular array elements, or it may lead to lots of extra bytes of information in an otherwise large, sparse array.

Still, if that solution has appeal, there's still one more approach that may be at least a little less kludgy. Rather than loop through the array to prepopulate it (or deal with CFTRY/ CFCATCH to detect errors), you could use CFPARAM within the loop while iterating through the array. This will assign a default empty string to any array elements that are otherwise "not defined," then test for that value to determine which array elements have value. The change to the loop above would be:

<CFLOOP FROM="1" TO="#ArrayLen(ACart)#" INDEX="i">
<CFPARAM NAME="Acart[i]" DEFAULT="">
<CFIF Acart[i] is not "">
Item: #ACart[i]# <br>
</CFIF>
</CFLOOP>
CFPARAM says, "If the named variable doesn't exist, create it and populate it with the given default value." Now, unlike the test for IsDefined(), the test that follows will never result in a runtime error, and it'll only print an array element if it has content. (If you need to distinguish between an element whose value is already an empty string and one whose value is assigned via CFPARAM, change the DEFAULT and test using some other unlikely value.)

Thanks to developer Tim Painter and instructor Emily Kim, who both shared this solution with me.

I hope this discussion of the problem is helpful for those facing this challenge. I welcome any thoughts on better approaches. My e-mail address is at the end of the article.

Part 2: Testing for Existence Within an Array of Structures
Maybe you don't have a problem with an array that's missing elements. However, a more practical extension of this problem is when you're looping over an array of structures and want to test whether an array element has all its keys.

Here's a practical example. Let's make our shopping cart array a little more advanced, using structures within it to hold multiple values of data for each item. Consider the following code:

<CFSET ACart = ArrayNew(1)>

<CFSET ACart[1] = StructNew()>
<CFSET ACart[1].item="Nokia 8150 phone">
<CFSET ACart[1].price="135.00">
<CFSET ACart[1].rebate="75.00">

<CFSET ACart[2] = StructNew()>
<CFSET ACart[2].item="Carrying case">
<CFSET ACart[2].price="35.00">

<CFOUTPUT>
<CFLOOP FROM="1" TO="#arraylen(ACart)#" INDEX="i">
Item: #ACart[i].item# <br>
Price: #ACart[i].price#<br>
Rebate: #ACart[i].rebate#
<hr>
</CFLOOP>
</CFOUTPUT>

Note that some of those structures have keys that the others don't. This code fails when it tries to print out the value of ACart[2].rebate, because there's no rebate for the second cart item (the "carrying case").

Note that this is not about missing array elements. It's about missing structure keys. They're different but might seem related.

Trying, Again, to Use IsDefined()
It's tempting to throw in a test with IsDefined() around the reference to rebate, to print a value only if it exists. Even if we're clever about the dynamic value of i, as in:

<CFIF IsDefined("ACart["&i&"].rebate")>
Rebate: #ACart[i].rebate#
<.CFIF>
we still get the error we saw above: Parameter 1 of function IsDefined which is now "ACart[1].rebate" must be a syntactically valid variable name

Again, ACart[1].rebate is a valid variable name, and the first element in the array and the rebate key in the structure exist. We're trying to refer to an array inside IsDefined() and it's not allowed - whether the instance is there or not.

Given that simple syntactical limitation, some clever folks may get around it by first assigning the structure in the given array element to a simple variable. This creates a copy (by reference) of the structure. Since it's no longer an array, we can test for its keys with IsDefined(), as in:

<CFSET test = ACart[i]> <CFIF IsDefined("test.rebate")> Rebate: #ACart[i].rebate# <.CFIF>

To the Rescue: StructKeyExists()
That two-step approach works, but there's an even easier approach using the StructKeyExists() function. This tests the existence of a given key in a structure and - here's the key point - it doesn't have a problem looking in an array of structures.

The solution would become:

<CFIF StructKeyExists(ACart[I], "rebate")>
Rebate: #ACart[i].rebate#
<.CFIF>

This solves the problem of a missing structure key (such as "rebate"), but it would still fail in the case of our sparse array from earlier. The ultimate solution is to also use CFPARAM, again, just inside the loop, to be able to assign a value to missing array elements. The question, then, is what to make the default.

Simply assigning an empty string to Acart[i] won't suffice, because the test for structkeyexists will complain if a given element of Acart[] is just a string (it expects a structure). The simple solution is to assign a default that creates a structure in the missing array element, as in:

<CFPARAM NAME="Acart[i]" DEFAULT="#StructNew()#">
Put that after the CFLOOP, and note that it's important not to leave out the pound signs around the StructNew function. Doing so would simply assign the string "StructNew()" to the array element, which would also lead to failure in the later IF test. (And you can't just leave off the quotes either: always use quotes around the value of an attribute to a CF - or indeed, HTML - tag. You may get away with it sometimes, but usually, as in this case, it won't provide the expected result.)

Structure Functions: Beware, and Some Bonus Topics
Note: Similar to most structure functions that work on structure keys, it expects the structure (the first parameter) to be the value of a structure and the second (the key) to be the name of the key. This means that in the example above and in most cases, the structure should not be in quotes while the key should be.

This often confuses folks when they begin working with structure functions, such as StructKeyExists and even StructDelete(). This nifty function can take advantage of the fact that sessions are indeed structures and can therefore be used to delete a given session variable (login, for instance) using:

#StructDelete(session,"login")#
Some people will be delighted to have read to this point as they've always wanted to be able to delete a particular session variable. That wasn't the point of the article, but let's consider it a bonus for being willing to consider all the ideas being offered here. (As of Release 4.5 you can also treat many variable scopes this way, including application, cgi, cookie, form, and url. You can't refer to client or server variables this way, though.)

One last point: Of course, if the name of the key to be deleted was stored as the value of a variable, the second parameter shouldn't be in quotes. The same is true for our StructKeyExists above. For instance, if we could loop through all the keys using <CFLOOP>'s COLLECTION attribute instead of hard-coding what we expected to find in the collection, as we did above:

...
<CFOUTPUT>
<CFLOOP FROM="1" TO="#ArrayLen(Acart)#" INDEX="i">
<CFLOOP COLLECTION="#Acart[i]#" ITEM="y">
<CFIF StructKeyExists(Acart[i], y)>
#y#: #Acart[i][y]#<br>
</CFIF>
</CFLOOP>
<hr>
</CFLOOP>
</CFOUTPUT>

the output would be:

ITEM: Nokia 8150 phone
PRICE: 135.00
REBATE: 75.00

ITEM: Carrying case
PRICE: 35.00

It's nifty if you didn't know you could loop through the structure that way. The important point is, the second parameter of StructKeyExists is "y". It's a variable driven by the CFLOOP COLLECTION, and its value will be "item", then "price", then "rebate" in the first array element, and "item", then "price" in the second.

You can loop through the variable structures we referred to earlier: session, application, cgi, cookie, form, and url. Try it using a variation of the code above; for a similar explanation see my article in last December's issue of CFDJ (Vol. 2, issue 12), "Toward Better Error Handling, Part 2," in which I showed the usefulness of looping through these structures to display their values when an error occurs.

Summary
I hope these solutions (testing for the existence of an array element and for a key in an array of structures, as well as deleting session variables and looping through structures) have been helpful.

If you haven't had these problems and still read to this point, I congratulate you. You'll now be armed when any of these problems do arise.

More Stories By Charlie Arehart

A veteran ColdFusion developer since 1997, Charlie Arehart is a long-time contributor to the community and a recognized Adobe Community Expert. He's a certified Advanced CF Developer and Instructor for CF 4/5/6/7 and served as tech editor of CFDJ until 2003. Now an independent contractor (carehart.org) living in Alpharetta, GA, Charlie provides high-level troubleshooting/tuning assistance and training/mentoring for CF teams. He helps run the Online ColdFusion Meetup (coldfusionmeetup.com, an online CF user group), is a contributor to the CF8 WACK books by Ben Forta, and is frequently invited to speak at developer conferences and user groups worldwide.

Comments (3) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Pablo 02/15/08 02:02:44 PM EST

will get the job done, but if you want a sparse array (i.e. one where only the elements that have data are initialized), then the try/catch will work better.

Sanka Suresh 08/05/04 01:51:37 AM EDT

This is really a very good artical... it helped me a lot!!!
Keep up the good work.

Sanka Suresh 08/05/04 01:51:33 AM EDT

This is really a very good artical... it helped me a lot!!!
Keep up the good work.

@ThingsExpo Stories
The BPM world is going through some evolution or changes where traditional business process management solutions really have nowhere to go in terms of development of the road map. In this demo at 15th Cloud Expo, Kyle Hansen, Director of Professional Services at AgilePoint, shows AgilePoint’s unique approach to dealing with this market circumstance by developing a rapid application composition or development framework.

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
“In the past year we've seen a lot of stabilization of WebRTC. You can now use it in production with a far greater degree of certainty. A lot of the real developments in the past year have been in things like the data channel, which will enable a whole new type of application," explained Peter Dunkley, Technical Director at Acision, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
DevOps Summit 2015 New York, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential.
"People are a lot more knowledgeable about APIs now. There are two types of people who work with APIs - IT people who want to use APIs for something internal and the product managers who want to do something outside APIs for people to connect to them," explained Roberto Medrano, Executive Vice President at SOA Software, in this SYS-CON.tv interview at Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Nigeria has the largest economy in Africa, at more than US$500 billion, and ranks 23rd in the world. A recent re-evaluation of Nigeria's true economic size doubled the previous estimate, and brought it well ahead of South Africa, which is a member (unlike Nigeria) of the G20 club for political as well as economic reasons. Nigeria's economy can be said to be quite diverse from one point of view, but heavily dependent on oil and gas at the same time. Oil and natural gas account for about 15% of Nigera's overall economy, but traditionally represent more than 90% of the country's exports and as...
The Internet of Things is a misnomer. That implies that everything is on the Internet, and that simply should not be - especially for things that are blurring the line between medical devices that stimulate like a pacemaker and quantified self-sensors like a pedometer or pulse tracker. The mesh of things that we manage must be segmented into zones of trust for sensing data, transmitting data, receiving command and control administrative changes, and peer-to-peer mesh messaging. In his session at @ThingsExpo, Ryan Bagnulo, Solution Architect / Software Engineer at SOA Software, focused on desi...
"At our booth we are showing how to provide trust in the Internet of Things. Trust is where everything starts to become secure and trustworthy. Now with the scaling of the Internet of Things it becomes an interesting question – I've heard numbers from 200 billion devices next year up to a trillion in the next 10 to 15 years," explained Johannes Lintzen, Vice President of Sales at Utimaco, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
"For over 25 years we have been working with a lot of enterprise customers and we have seen how companies create applications. And now that we have moved to cloud computing, mobile, social and the Internet of Things, we see that the market needs a new way of creating applications," stated Jesse Shiah, CEO, President and Co-Founder of AgilePoint Inc., in this SYS-CON.tv interview at 15th Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Gridstore™, the leader in hyper-converged infrastructure purpose-built to optimize Microsoft workloads, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Gridstore™ is the leader in hyper-converged infrastructure purpose-built for Microsoft workloads and designed to accelerate applications in virtualized environments. Gridstore’s hyper-converged infrastructure is the industry’s first all flash version of HyperConverged Appliances that include both compute and storag...
Today’s enterprise is being driven by disruptive competitive and human capital requirements to provide enterprise application access through not only desktops, but also mobile devices. To retrofit existing programs across all these devices using traditional programming methods is very costly and time consuming – often prohibitively so. In his session at @ThingsExpo, Jesse Shiah, CEO, President, and Co-Founder of AgilePoint Inc., discussed how you can create applications that run on all mobile devices as well as laptops and desktops using a visual drag-and-drop application – and eForms-buildi...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
Code Halos - aka "digital fingerprints" - are the key organizing principle to understand a) how dumb things become smart and b) how to monetize this dynamic. In his session at @ThingsExpo, Robert Brown, AVP, Center for the Future of Work at Cognizant Technology Solutions, outlined research, analysis and recommendations from his recently published book on this phenomena on the way leading edge organizations like GE and Disney are unlocking the Internet of Things opportunity and what steps your organization should be taking to position itself for the next platform of digital competition.
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at @ThingsExpo, Andrew Bolwell, Director of Innovation for HP's Printing and Personal Systems Group, discussed how key attributes of mobile technology – touch input, sensors, social, and ...