ColdFusion Muse

Ask-A-Muse: Duplicating PHP Array Syntax In Coldfusion

Mark Kruger July 3, 2006 6:07 AM Coldfusion Tips and Techniques Comments (1)

CF Muse Reader, Rashid Aslam Asks:
Can i do the same kind of array initialization in Coldfusion as I do in PHP. Like This:

    $lang['abrvdays'] = array("Sun", "Mon", "Tue");

Actually, using a list to create an array in Coldfusion is slightly easier than creating and populating an array from scratch. Instead of arrayNew() followed by set statements you can simply use the listToArray() function.

<cfset abrvdays = listToArray("Sun,Mon,Tues")>
It takes a list, like the one above and there is an optional "delimiters" argument that you can include as well. For example, to create an array from my domain name I could specify periods like so:
<cfset arrDomain = listToArray("www.coldfusionmuse.com",".")>

  • Share:

1 Comments

  • Dan G. Switzer, II's Gravatar
    Posted By
    Dan G. Switzer, II | 7/3/06 1:54 PM
    You could also do something like:

    <cffunction name="arrayCreate" returntype="array">
       <cfset var aReturn = arrayNew(1) />
       <cfset var i = 0 />
       <cfloop index="i" from="1" to="#arrayLen(arguments)#">
          <!---//
             you might want to using duplicate(arguments[i])
             if you plan on using complex array items
          //--->
          <cfset arrayAppend(aReturn, arguments[i]) />
       </cfloop>
       <cfreturn aReturn />
    </cffunction>

    <cfdump var='#arrayCreate("one", "two", "three", "four")#'>

    One of the benefits of doing this over using listToArray() is you don't have to worry about trying to escape out the delimiter or having the delimiter being used in your value--thus throwing over your array.