Tech Tip: Stepping Through a Collection with a For-Loop
PRODUCT: 4D | VERSION: 17 | PLATFORM: Mac & Win
Published On: May 4, 2018
Collections are a new data type, and as such they will come with some learning curve but if given the time will prove to be a valuable asset to developing in 4D. One such curve to learn is using a collection with a for-loop.
When stepping through an array in a for-loop, the code looks like this:
For ($i;1;Size of array($some_array)) // do something with array values $arr_val:=$some_array{$i} End for |
When stepping through a collection, the for-loop is setup slightly differently because, unlike the array, the collection starts indexing at "0" instead of "1":
For ($i;0;$some_collection.length-1) // do something with collection values $col_val:=$some_collection[$i] End for |
Important in the above is to have object notation turned on, as the built in length property of the collection is used as the end value of the for-loop, in place of the Size of array command used with arrays.
So why iterate the for-loop from 0 to length-1?
This is because the collection starts the index at 0, which is also counted in the length, so the last index of the collection for a collection with 5 elements would be 4, hence why length-1 is used to end the for-loop.
Alternatively, the for-loop for the collection could be written like this to achieve the same results:
For ($i;1;$some_collection.length) // do something with collection values $col_val:=$some_collection[$i-1] End for |
In version 17, there will be yet another way to loop through a collection using a new statement For each/End for each. Example below, each element of the collection is iterated through and returned in the $item variable:
For each($item;$some_collection) // do something with collection values $col_val:=$item End for each |