4D v17.4

For each...End for each

Home

 
4D v17.4
For each...End for each

For each...End for each  


 

 

The formal syntax of the For each...End for each control flow structure is:

 For each(Current_Item;Expression{;begin{;end}}){Until|While}(Boolean_Expression)}
 statement(s)
End for each

The For each...End for each structure iterates a specified Current_item over all values of the Expression. The Current_item type depends on the Expression type. The For each...End for each loop can iterate through three Expression types:

  • collections: loop through each element of the collection,
  • entity selections: loop through each entity,
  • objects: loop through each object property.

The following table compares the three types of For each...End for each:

Loop through collectionsLoop through entity selectionsLoop through objects
Current_Item typeVariable of the same type as collection elementsEntityText variable
Expression typeCollection (with elements of the same type)Entity selectionObject
Number of loops (by default)Number of collection elementsNumber of entities in the selectionNumber of object properties
Support of begin / end parametersYesYesNo
  • The number of loops is evaluated at startup and will not change during the processing. Adding or removing items during the loop is usually not recommended since it may result in missing or redundant iterations.
  • By default, the enclosed statement(s) are executed for each value in Expression. It is, however, possible to exit the loop by testing a condition either at the begining of the loop (While) or at the end of the loop (Until).
  • The begin and end optional parameters can be used with collections and entity selections to define boundaries for the loop.

When For each...End for each is used with an Expression of the Collection type, the Current_Item parameter is a variable of the same type as the collection elements. By default, the number of loops is based on the number of items of the collection.

The collection must contain only elements of the same type, otherwise an error will be returned as soon as the Current_Item variable is assigned the first mismatched value type.

At each loop iteration, the Current_Item variable is automatically filled with the matching element of the collection. The following points must be taken into account:

  • If the Current_Item variable is of the object type or collection type (i.e. if Expression is a collection of objects or of collections), modifying this variable will automatically modify the matching element of the collection (because objects and collections share the same references). If the variable is of a scalar type, only the variable will be modified.
  • The Current_Item variable must be of the same type as the collection elements. If any collection item is not of the same type as the variable, an error is generated and the loop stops.
  • If the collection contains elements with a Null value, an error will be generated if the Current_Item variable type does not support Null values (such as longint variables).
Example  

You want to compute some statistics for a collection of numbers:

 C_COLLECTION($nums)
 $nums:=New collection(10;5001;6665;33;1;42;7850)
 C_LONGINT($item;$vEven;$vOdd;$vUnder;$vOver)
 For each($item;$nums)
    If($item%2=0)
       $vEven:=$vEven+1
    Else
       $vOdd:=$vOdd+1
    End if
    Case of
       :($item<5000)
          $vUnder:=$vUnder+1
       :($item>6000)
          $vOver:=$vOver+1
    End case
 End for each
  //$vEven=3, $vOdd=4
  //$vUnder=4,$vOver=2

When For each...End for each is used with an Expression of the Entity selection type, the Current_Item parameter is the entity that is currently processed.

The number of loops is based on the number of entities in the entity selection. On each loop iteration, the Current_Item parameter is automatically filled with the entity of the entity selection that is currently processed.

Note: If the entity selection contains an entity that was removed meanwhile by another process, it is automatically skipped during the loop.

Keep in mind that any modifications applied on the current entity must be saved explicitly using entity.save( ).

Example  

You want to raise the salary of all British employees in an entity selection:

 C_OBJECT(emp)
 For each(emp;ds.Employees.query("country='UK'"))
    emp.salary:=emp.salary*1,03
    emp.save()
 End for each

When For each...End for each is used with an Expression of the Object type, the Current_Item parameter is a text variable automatically filled with the name of the currently processed property. 

The properties of the object are processed according to their order of creation. During the loop, properties can be added to or removed from the object, without modifying the number of loops that will remain based on the original number of properties of the object.

Example  

You want to switch the names to uppercase in the following object:

{
    "firstname": "gregory",
    "lastname": "badikora",
    "age": 20
}

You can write:

 For each(property;vObject)
    If(Value type(vObject[property])=Is text)
       vObject[property]:=Uppercase(vObject[property])
    End if
 End for each

{
    "firstname": "GREGORY",
    "lastname": "BADIKORA",
    "age": 20
}

You can define bounds to the iteration using the optional begin and end parameters.

Note: The begin and end parameters can only be used in iterations through collections and entity selections (they are ignored on object properties).

  • In the begin parameter, pass the element position in Expression at which to start the iteration (begin is included).
  • In the end parameter, you can also pass the element position in Expression at which to stop the iteration (end is excluded). 

If end is omitted or if end is greater than the number of elements in Expression, elements are iterated from begin until the last one (included).

If the begin and end parameters are positive values, they represent actual positions of elements in Expression.

If begin is a negative value, it is recalculed as begin:=begin+Expression size (it is considered as the offset from the end of Expression). If the calculated value is negative, begin is set to 0.
Note: Even if begin is negative, the iteration is still performed in the standard order.
If end is a negative value, it is recalculed as end:=end+Expression size

For example:

  • a collection contains 10 elements (numbered from 0 to 9)
  • begin=-4 -> begin=-4+10=6 -> iteration starts at the 6th element (#5)
  • end=-2 -> end=-2+10=8 -> iteration stops before the 8th element (#7), i.e. at the 7th element.
Example  

 C_COLLECTION($col;$col2)
 $col:=New collection("a";"b";"c";"d";"e")
 $col2:=New collection(1;2;3)
 C_TEXT($item)
 For each($item;$col;0;3)
    $col2.push($item)
 End for each
  //$col2=[1,2,3,"a","b","c"]
 For each($item;$col;-2;-1)
    $col2.push($item)
 End for each
  //$col2=[1,2,3,"a","b","c","d"]

You can control the For each...End for each execution by adding an Until or a While condition to the loop. When an Until(condition) or a While(condition) statement is associated to the loop, the iteration will stop as soon as the condition is evaluated to true.

You can pass either keyword depending on your needs:

  • The Until condition is tested at the end of each iteration, so if the Expression is not empty or null, the loop will be executed at least once.
  • The While condition is tested at the beginning of each iteration, so according to the condition result, the loop may not be executed at all.
Example  

 $colNum:=New collection(1;2;3;4;5;6;7;8;9;10)
 
 $total:=0
 For each($num;$colNum)While($total<30) //tested at the beginning
    $total:=$total+$num
 End for each
 ALERT(String($total)) //$total = 36 (1+2+3+4+5+6+7+8)
 
 $total:=1000
 For each($num;$colNum)Until($total>30) //tested at the end
    $total:=$total+$num
 End for each
 ALERT(String($total)) //$total = 1001 (1000+1)

The For each...End for each loop can be used on a shared collection or a shared object.

If your code needs to modify one or more element(s) of the collection or object properties, you need to use the Use...End use keywords. Depending on your needs, you can call the Use...End use keywords:

  • before entering the loop, if items should be modified together for integrity reasons, or
  • within the loop when only some elements/properties need to be modified and no integrity management is required.

 
PROPERTIES 

Product: 4D
Theme: Language definition

 
PAGE CONTENTS 
 
HISTORY 

New
Created: 4D v17

 
ARTICLE USAGE

4D Language Reference ( 4D v17)
4D Language Reference ( 4D v17.1)
4D Language Reference ( 4D v17.2)
4D Language Reference ( 4D v17.3)
4D Language Reference ( 4D v17.4)