foreach (__key*, __value in __collection)

Description

Used for control structures. See also if, else and while.

Iterates over all items in the provided collection or iterator, putting key (optional) and value into the provided variables. The code block following the foreach statement, enclosed in curly brackets, will be run once for every element. If the variable to be looped is atomic (but not an iterator), there are two cases built for convenience:

  • A null value will be treated as an empty list, which runs the code block zero times
  • An atomic value that is not null will be treated as a list with that value as its only element, which runs the code block once

Examples

An example of looping through a basic list:

use System;
var items = [1,2,3,4,5,6,7,8,9];
foreach(item in items){
    System.print(item);
}
An example of looping through an object:
use System;
var items = {
    "a":1,
    "b":2,
    "c":"something"
};
foreach(key, value in items){
    System.print(key :: " = " :: value);
}

An example of looping through links on a page:

use System;
use Web;

// Process links on the page
var page = Web.loadPage("http://www.xillio.com");
var links = Web.xPath(page, "//a");
foreach(numberinlevel, link in links) {
    var url = Web.xPath(link, "./@href");
    var linktext = Web.xPath(link,"./text()");
    System.print(linktext :: " | " :: url);
}