xHarbour Reference Documentation > Statement Reference |
Iterates elements of data types that can be seen as a collection.
FOR EACH <element> IN <array>|<object>|<string> <statements> [LOOP] <statements> [EXIT] NEXT
The FOR EACH statement forms a control structure that executes a block of statements for a data type containing multiple elements. This can be data of type Array, Object or Character string. The loop iterates all elements contained in the data and assigns the value of the next element to <element> on each iteration.
FOR EACH is similar to the regular FOR loop. But it completes considerably faster than a FOR loop, since there is no explicit loop counter. In contrast, FOR EACH uses an implicit loop counter whose value can be queried using the function HB_EnumIndex(). Other than this, LOOP and EXIT statements within the loop are treated the same as in a FOR loop.
When FOR EACH statements are nested, each loop maintains its own counter, i.e. HB_EnumIndex() retrieves the counter of the loop that is currently executed. When the FOR EACH loop is finished, its loop counter is set to 0.
See also: | AEval(), HB_EnumIndex(), FOR, DO CASE, DO WHILE, IF, SWITCH, WITH OBJECT |
Category: | Control structures , Statements , xHarbour extensions |
// The example demonstrates the FOR EACH statement using two // nested loops. The outer loop iterates an array while the // inner loop iterates character strings. PROCEDURE Main() LOCAL aArray := { "Hello", "World" } LOCAL cString, cChar FOR EACH cString IN aArray ? "----- Outer loop -----" ? HB_EnumIndex(), cString ? "----- Inner loop -----" FOR EACH cChar IN cSTring ? HB_EnumIndex(), cChar NEXT NEXT ? "-------- End ---------" ? HB_EnumIndex() RETURN /* Output of example: ----- Outer loop ----- 1 Hello ----- Inner loop ----- 1 H 2 e 3 l 4 l 5 o ----- Outer loop ----- 2 World ----- Inner loop ----- 1 W 2 o 3 r 4 l 5 d -------- End --------- 0 */
http://www.xHarbour.com