Welcome!

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 only place to be June 9-11 is Cloud Expo & @ThingsExpo 2015 East at the Javits Center in New York City. Join us there as delegates from all over the world come to listen to and engage with speakers & sponsors from the leading Cloud Computing, IoT & Big Data companies. Cloud Expo & @ThingsExpo are the leading events covering the booming market of Cloud Computing, IoT & Big Data for the enterprise. Speakers from all over the world will be hand-picked for their ability to explore the economic strategies that utility/cloud computing provides. Whether public, private, or in a hybrid form, clo...
SYS-CON Events announces a new pavilion on the Cloud Expo floor where WebRTC converges with the Internet of Things. Pavilion will showcase WebRTC and the Internet of Things. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices--computers, smartphones, tablets, and sensors – connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
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 Internet of @ThingsExpo, Andrew Bolwell, Director of Innovation for HP’s Printing and Personal Systems Group, will discuss how key attributes of mobile technology – touch input, senso...
SYS-CON Events announced today that Gridstore™, the leader in software-defined storage (SDS) purpose-built for Windows Servers and Hyper-V, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Gridstore™ is the leader in software-defined storage purpose built for virtualization that is designed to accelerate applications in virtualized environments. Using its patented Server-Side Virtual Controller™ Technology (SVCT) to eliminate the I/O blender effect and accelerate applications Gridsto...
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, will examine three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
The Internet of Things (IoT) promises to evolve the way the world does business; however, understanding how to apply it to your company can be a mystery. Most people struggle with understanding the potential business uses or tend to get caught up in the technology, resulting in solutions that fail to meet even minimum business goals. In his session at Internet of @ThingsExpo, Jesse Shiah, CEO / President / Co-Founder of AgilePoint Inc., will show what is needed to leverage the IoT to transform your business. He will discuss opportunities and challenges ahead for the IoT from a market and tec...
SYS-CON Events announced today that TeleStax, the main sponsor of Mobicents, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. TeleStax provides Open Source Communications software and services that facilitate the shift from legacy SS7 based IN networks to IP based LTE and IMS networks hosted on private (on-premise), hybrid or public clouds. TeleStax products include Restcomm, JSLEE, SMSC Gateway, USSD Gateway, SS7 Resource Adaptors, SIP Servlets, Rich Multimedia Services, Presence Services/RCS, Diame...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that O'Reilly Media has been named “Media Sponsor” of SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. O'Reilly Media spreads the knowledge of innovators through its books, online services, magazines, and conferences. Since 1978, O'Reilly Media has been a chronicler and catalyst of cutting-edge development, homing in on the technology trends that really matter and spurring their adoption by amplifying "faint signals" from the alpha geeks who are creating the future. An...
SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Transparent Cloud-computing Consortium (abbreviation: T-Cloud Consortium) will conduct research activities into changes in the computing model as a result of collaboration between "device" and "cloud" and the creation of new value and markets through organic data processing High speed and high quality networks, and dramatic improvements in computer processing capabilities, have greatly changed the nature of applications and made the storing and processing of data on the network commonplace.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
As a disruptive technology, Web Real-Time Communication (WebRTC), which is an emerging standard of web communications, is redefining how brands and consumers communicate in real time. The on-going narrative around WebRTC has largely been around incorporating video, audio and chat functions to apps. In his session at Internet of @ThingsExpo, Alex Gouaillard, Founder and CTO of Temasys Communications, will look at a fourth element – data channels – and talk about its potential to move WebRTC beyond browsers and into the Internet of Things.
SYS-CON Events announced today that Gigaom Research has been named "Media Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Ashar Baig, Research Director, Cloud, at Gigaom Research, will also lead a Power Panel on the topic "Choosing the Right Cloud Option." Gigaom Research provides timely, in-depth analysis of emerging technologies for individual and corporate subscribers. Gigaom Research's network of 200+ independent analysts provides new content daily that bridges the gap between break...
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...
The Industrial Internet revolution is now underway, enabled by connected machines and billions of devices that communicate and collaborate. The massive amounts of Big Data requiring real-time analysis is flooding legacy IT systems and giving way to cloud environments that can handle the unpredictable workloads. Yet many barriers remain until we can fully realize the opportunities and benefits from the convergence of machines and devices with Big Data and the cloud, including interoperability, data security and privacy.
Swiss innovators dizmo Inc. launches its ground-breaking software, which turns any digital surface into an immersive platform. The dizmo platform seamlessly connects digital and physical objects in the home and at the workplace. Dizmo breaks down traditional boundaries between device, operating systems, apps and software, transforming the way users work, play and live. It supports orchestration and collaboration in an unparalleled way enabling any data to instantaneously be accessed on any surface, anywhere and made interactive. Dizmo brings fantasies as seen in Sci-fi movies such as Iro...