Tuesday, January 26, 2010

Comparing Two Arrays in CFML

This came up yesterday in a discussion with a friend of mine. He had two arrays and he wanted to see if they were identical in terms of order and value of the elements. His first thought was to loop through the arrays and compare each element, but since CFML arrays are really Java arrays, there's a much simpler way.

arrray1 = ArrayNew(1);
array1[1] = "foo";
array1[2] = "bar";

array2 = ArrayNew(1);
array2[1] = "foo";
array2[2] = "bar";

arraysAreEqual = array1.equals(array2);

The equals() method on the array returns a boolean and tells you whether or not the arrays are identical in terms of the values and ordering of the array elements. Note that if the values are identical but in a different order, the arrays will not be considered equal, so sort before doing this test if there's a chance things might be in a different order between the two arrays.


ElliottZ said...

Note that this is case sensitive, and has unexpected results on arrays of non strings, even if they are "simple" values in CF. CF stores numbers, dates and booleans as strings, java equivalent types or numbers depending on lots of factors.a1 = arrayNew(1);a1[1] = 1+0;a2 = arrayNew(1);a2[1] = 1; // Not equal, but "equal" in CF sense.assertFalse( a1.equals(a2) );You'd be better off writing your own function. There's too many cases where equals() will return false.

Matthew Woodward said...

In this case it was all strings. I would expect it to be case sensitive, but good point about the numeric data types. I still think it's handy for strings though.

Matthew Woodward said...

Actually the example you provided works correctly in OpenBD, so the issue with numeric datatypes must be specific to Adobe CF.