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)

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.


@ThingsExpo Stories
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
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...
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 Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
SYS-CON Events announced today that SOA Software, an API management leader, 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. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
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 Utimaco 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. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
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...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

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 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.
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...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
Predicted by Gartner to add $1.9 trillion to the global economy by 2020, the Internet of Everything (IoE) is based on the idea that devices, systems and services will connect in simple, transparent ways, enabling seamless interactions among devices across brands and sectors. As this vision unfolds, it is clear that no single company can accomplish the level of interoperability required to support the horizontal aspects of the IoE. The AllSeen Alliance, announced in December 2013, was formed with the goal to advance IoE adoption and innovation in the connected home, healthcare, education, aut...