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
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, discussed single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example t...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at @ThingsExpo, Robin Raymond, Chief Architect at Hookflash, will walk through the shifting landscape of traditional telephone and voice services ...
The Domain Name Service (DNS) is one of the most important components in networking infrastructure, enabling users and services to access applications by translating URLs (names) into IP addresses (numbers). Because every icon and URL and all embedded content on a website requires a DNS lookup loading complex sites necessitates hundreds of DNS queries. In addition, as more internet-enabled ‘Things' get connected, people will rely on DNS to name and find their fridges, toasters and toilets. According to a recent IDG Research Services Survey this rate of traffic will only grow. What's driving t...
Enthusiasm for the Internet of Things has reached an all-time high. In 2013 alone, venture capitalists spent more than $1 billion dollars investing in the IoT space. With "smart" appliances and devices, IoT covers wearable smart devices, cloud services to hardware companies. Nest, a Google company, detects temperatures inside homes and automatically adjusts it by tracking its user's habit. These technologies are quickly developing and with it come challenges such as bridging infrastructure gaps, abiding by privacy concerns and making the concept a reality. These challenges can't be addressed w...
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
The definition of IoT is not new, in fact it’s been around for over a decade. What has changed is the public's awareness that the technology we use on a daily basis has caught up on the vision of an always on, always connected world. If you look into the details of what comprises the IoT, you’ll see that it includes everything from cloud computing, Big Data analytics, “Things,” Web communication, applications, network, storage, etc. It is essentially including everything connected online from hardware to software, or as we like to say, it’s an Internet of many different things. The difference ...
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world.
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.
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, 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...
An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...

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...

The security devil is always in the details of the attack: the ones you've endured, the ones you prepare yourself to fend off, and the ones that, you fear, will catch you completely unaware and defenseless. The Internet of Things (IoT) is nothing if not an endless proliferation of details. It's the vision of a world in which continuous Internet connectivity and addressability is embedded into a growing range of human artifacts, into the natural world, and even into our smartphones, appliances, and physical persons. In the IoT vision, every new "thing" - sensor, actuator, data source, data con...
Technology is enabling a new approach to collecting and using data. This approach, commonly referred to as the "Internet of Things" (IoT), enables businesses to use real-time data from all sorts of things including machines, devices and sensors to make better decisions, improve customer service, and lower the risk in the creation of new revenue opportunities. In his General Session at Internet of @ThingsExpo, Dave Wagstaff, Vice President and Chief Architect at BSQUARE Corporation, discuss the real benefits to focus on, how to understand the requirements of a successful solution, the flow of ...
"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.
Focused on this fast-growing market’s needs, Vitesse Semiconductor Corporation (Nasdaq: VTSS), a leading provider of IC solutions to advance "Ethernet Everywhere" in Carrier, Enterprise and Internet of Things (IoT) networks, introduced its IStaX™ software (VSC6815SDK), a robust protocol stack to simplify deployment and management of Industrial-IoT network applications such as Industrial Ethernet switching, surveillance, video distribution, LCD signage, intelligent sensors, and metering equipment. Leveraging technologies proven in the Carrier and Enterprise markets, IStaX is designed to work ac...
C-Labs LLC, a leading provider of remote and mobile access for the Internet of Things (IoT), announced the appointment of John Traynor to the position of chief operating officer. Previously a strategic advisor to the firm, Mr. Traynor will now oversee sales, marketing, finance, and operations. Mr. Traynor is based out of the C-Labs office in Redmond, Washington. He reports to Chris Muench, Chief Executive Officer. Mr. Traynor brings valuable business leadership and technology industry expertise to C-Labs. With over 30 years' experience in the high-tech sector, John Traynor has held numerous...
The 3rd International @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 it is now accepting Keynote Proposals. 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.