Like many other programming languages, 4D provides the ability to iterate over numbers with a For(…) / End for statement, or over a condition thanks to the While(…)/End while and Repeat/Until(…) keywords. These iterations (or loops) are very useful, but not the most appropriate way to iterate over advanced data types such as collections and entity selections. That’s why the new For each(…)/End for each iterator has been created, to help ease your coding!
Looping THROUGH collection items
The For each / End for each statement can be used in several cases. One case is to looping through items of a collection. No need to have advance knowledge of how many items belong to the collection before entering the loop. At each iteration, the variable passed as first parameter (item) will be filled with the current item of the collection (col).
col:=New collection("charlie";"delta";"uniform";"foxtrot";"quebec")
$count:=0
For each (item;col)
If (Length(item)>5)
$count:=$count+1
End if
End for each
ALERT(String($count)+" words found!")
Looping through entities
The second case is also the newest one: looping through entities of an entity selection. Entities and entity selections are part of a new concept in 4D, described in this blog post. The main thing you need to know is that entities are similar to records, and entity selections can be compared to traditional selections, but they’re both declared as objects!
Again, no need for prior knowledge of how many entities belong to the entity selection before entering the loop. At each iteration, the entity variable passed as first parameter will be automatically filled with the current entity of the entity selection.
UK_emps:=ds.Employees.query("country='UK'")
// Browse the entity selection
For each (emp;UK_emps)
emp.salary:=emp.salary*1.03 // raise the salary
emp.save() // save the result
End for each
Looping Through object properties
The For each / End for each statement can also be used in another case: looping through object properties. For example, it can be very useful in case you want to write some generic code, without knowing the object property names in advance.
Again, no need to know beforehand how many properties an object has before entering the loop! All of its properties’ names will be parsed one by one! At each iteration, the variable passed as first parameter (property in the example below) will be filled with the attribute name of the object ($contact in the example below).
For each ($property;$contact)
If (Value type($contact[$property])=Is text)
//Change to uppercase each attribute which is a text
$contact[$property]:=Uppercase($contact[$property])
End if
End for each