KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Understanding for Each...While Behavior in 4D
PRODUCT: 4D | VERSION: 21 | PLATFORM: Mac & Win
Published On: December 19, 2025
The For each loop in 4D can iterate through three expression types:
  • Collections – iterates through each element

  • Entity selections – iterates through each entity

  • Objects – iterates through each property

When combined with a While clause, the loop continues as long as the condition remains true.
In a For each … While loop, the iterator moves to the next element before evaluating the While condition.
As a result:
  • If the condition becomes false in the middle of the collection, the loop stops but the loop variable already contains the next element.

  • If the condition becomes false on the last element, there is no next element, so the loop variable keeps the last value.

Example:

$col:=New collection(10; 20; 30; 40)
$run:=True

For each ($v; $col) While ($run)
   If ($v=30)
    $run:=False
   End if
End for each

In this example, when $v = 30, the condition becomes false during the next iteration check, so $v ends up containing 40 when the loop exits.

Please note that the While clause can be replaced by Until clause as well.