Check if a ColdFusion Array Position Exists
Posted by Stephen Weyrick | Tags: coldfusion
This is some sample script that I used today to check if a position in an array exists. Basically, I was tasked with creating an email that showed hours from two separate datasources, and I needed to combine those side by side in an array to show the differences. I knew that the first set of hours would always exist, so I looped over the second set of hours with a nested loop matching up the dates. To check if the second position existed, I used a cfparam with set values of zero. I did this because ColdFusion doesn't seem to have clean way of checking for a missing element.
<cfloop from="1" to="#arrayLen(totalArr)#" index="a">
<cfset mytotals = structNew()/>
<cfset mytotals["date"] = totalDate[a] />
<cfset mytotals["hours"] = totalArr[a] />
<cfif arrayLen(totalUni) >
<cfloop from="1" to="#arrayLen(totalUni)#" index="hh">
<cfparam name="mytotals.unihours" type="string" default="0"/>
<cfif trim(totalDateUni[hh]) EQ trim(totalDate[a]) >
<cfset mytotals["unihours"] = totalUni[hh] />
</cfif>
</cfloop>
<cfelse>
<cfset mytotals["unihours"] = 0 />
</cfif>
<cfset arrayappend(myRetArray, mytotals) />
</cfloop>
If there is a better way to do this, I would love to know how.
8 responses so far ↓
Leave a Comment