I realize that the title implies a super basic topic, and it certainly does. But this is something that tripped me up a little earlier today so I thought that simple as it may be I would share for anyone else encountering a similar problem. My issue was that I created a list, looped over the list, for each loop checked the value, and depending on the value output a new value. What I found was that my switch statements would pick up the first value in the list but not the rest. The problem ended up being that I was putting a space between my comma and the next value. Let’s look at a quick example of this.
<!--- SET A LIST ---> <cfset VARIABLES.list = "RI, MA, CT"> <!--- LOOP OVER LIST ---> <cfloop list="#VARIABLES.list#" delimiters="," index="VARIABLES.i"> <!--- CHECK ITEM IN LIST AND SHOW FULL STATE NAME ---> <cfswitch expression="#VARIABLES.i#"> <cfcase value="RI"> <cfset VARIABLES.state = "Rhode Island"> </cfcase> <cfcase value="MA"> <cfset VARIABLES.state = "Massachusetts"> </cfcase> <cfcase value="CT"> <cfset VARIABLES.state = "Connecticut"> </cfcase> </cfswitch> <!--- DISPLAY FULL STATE NAME ---> <cfoutput> #VARIABLES.state#<br /> </cfoutput> </cfloop>
This will display “Rhode Island” three times. What causes this? Again it’s that space after the commas in my initial list. As it stands the the case value is looking for ” MA” not “MA”.
If you convert the items in the list into a byte array you will see that both MA and CT have an extra character which is a space. Simple and obvious solution though. Just make sure that your lists are nice and tight. While I have a tendency to use arrays as opposed to lists in these cases I really find it hard to believe that I’m just now noticing this.