2

I would like to use scopes for my array variable names.

This example works.

<cfset person_first_name[1] = "John">
<cfset person_first_name[2] = "Jack">
<cfset x = ArrayLen(person_first_name)>

However, this code occures the following error: "Object of type class coldfusion.runtime.Struct cannot be used as an array"

<cfset person.first_name[1] = "John">
<cfset person.first_name[2] = "Jack">
<cfset x = ArrayLen(person.first_name)>

Isn't it possible to name the variables like that?

7
  • 2
    What version of CF? I recall some instances of CF treating complex variable declatations like that as structures, not arrays. Explicitly declaring the subkey, person.first_name as an array first got around the issue. I.e. person.first_name = [], then appending values to it, or initializing it in one line like person.first_name = ["John","Jack"] Commented Mar 12, 2021 at 15:04
  • 1
    I use CF2018. The declaration works, the error doesnt occure anymore. Thanks for that hint. There are a lot more variables like id, last_name or dob. I get the data from a query and fill the array during the loop. Commented Mar 12, 2021 at 15:17
  • Not sure what the code is doing, but might consider leaving it as a query or using an array of structures instead, which is a lot more intuitive imo :) Like personArray[1] = { first_name = "...", dob = "..."}, etc... Commented Mar 12, 2021 at 15:19
  • My intention is to separate data processing and output from each other and to make my code, file and directory structure cleaner and more comprehensible. I prefer the spelling with a dot. On the left is the type of data and on the right of the dot what information it is. The arrays are filled in a loop over the query result. For output, I loop over the array and access the individual data via the index: <cfloop array="#person.id#" index="i">#person.id[i]# #person.first_name[i]# #person.last_name[i]#<br></cfloop>. Commented Mar 12, 2021 at 16:00
  • And there is another aspect. To generate less code I would like to use the same code or the same functions for selecting and outputting a single data record (e.g. for a form) or for a list. A single data record is then an array with only one element. Commented Mar 12, 2021 at 16:04

1 Answer 1

3

Adding a declaration for the array solved the problem. Thanks @SOS.

<cfset person.first_name = []>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.