Ask a Jedi: "Object of type class.lang.Boolean cannot be used as an array"

Darren asks:

is there anything wrong with this function because when i invoke it i get a weird error i don't understand which is "Object of type class.lang.Boolean cannot be used as an array" all i'm doing is query the db and compiling it into a 1 dimensional array. heres the function (some stuff deleted)
<cfquery name="getExtraImages" datasource="#request.dsn#"> SELECT * FROM extraimages </cfquery>
<cfset imageArray = arrayNew(1)>
<cfloop query="getExtraImages" startrow="1" endrow="#getExtraImages.recordcount#">
<cfset imageArray = arrayAppend(imageArray, "#extraImagePath#")>
</cfloop>

This is a simple problem, and one I see often. I’m pretty sure I answered this question before on the blog before, but as I said - it shows up often. The problem is the arrayAppend function. You would think that it takes an array, a value to add to it, and returns the new (larger) array. Instead, the function changes the array you pass to it directly and returns true or false. Now - I’ve never seen arrayAppend return false before, so it isn’t something you have to worry about checking, but you do need to ensure you use it the right way. I’d change his line above to:

<cfset arrayAppend(imageArray, extraImagePath)>

Note that I removed the unnecessary pound signs as well. If that line confuses you, you can think of it like running a function and assigning to nothing. Imagine this:

<cfset temp = arrayAppend(imageArray, extraImagePath)>

Now imagine you don’t need temp. That’s where the shorter syntax is useful.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments