How to create an array in ColdFusion

198 views Asked by At

Can anyone tell me how to convert this line of PHP to ColdFusion?

$dev_name = "xxx";
$cert_name = "yyy";
$url = "https://xxxx.com/";
$headers = array("X-BONANZLE-API-DEV-NAME: " . $dev_name 
                  , "X-BONANZLE-API-CERT-NAME: " . $cert_name);

Which is an array. I have tried this but it fails.

<cfset dev_name="xxx">
<cfset cert_name ="yyy">
<cfset headers = {X-BONANZLE-API-DEV-NAME:"#dev_name#"
                    , X-BONANZLE-API-CERT-NAME:"#cert_name#"}>

<cfdump var="#headers#">

</cfdump>
1

There are 1 answers

5
M.Scherzer On BEST ANSWER

You need to quote the key names also same as you did in the PHP version.

The issue that you are hitting is that your key names contain a "minus" character. To workaround this issue you need to quote your keyname.

Also in your sample CFML code you will end up creating a struct, it looks to me what you want is an array of structs.

So something like this should get you what you want:

<cfset headers = [ {"X-BONANZLE-API-DEV-NAME":"#dev_name#"}
                   , {"X-BONANZLE-API-CERT-NAME":"#cert_name#"} ]>

or if you just want an array of strings:

<cfset headers = [ "X-BONANZLE-API-DEV-NAME:" & dev_name
                   ,"X-BONANZLE-API-CERT-NAME:" & cert_name ]>

Note: the square brackets which indicate that you want an array and the curly braces indicate you want a struct. It's very similar to JSON notation.

If you are on an old version of coldfusion you would need to do something like this:

For a array of structs:

<cfset headers = arrayNew(1)>
<cfset headers[1] = structNew()>
<cfset headers[1]["X-BONANZLE-API-DEV-NAME"] = dev_name>
<cfset headers[2] = structNew()>
<cfset headers[2]["X-BONANZLE-API-CERT-NAME"] = cert_name>

OR

For a array of strings:

<cfset headers = arrayNew(1)>
<cfset headers[1] = "X-BONANZLE-API-DEV-NAME:" & dev_name>
<cfset headers[2] = "X-BONANZLE-API-CERT-NAME:" & cert_name>