Loops
A loop is the programming term for running the same chunk of code over and over.
In 99% of these case, you’ll be using a foreach loop.
Foreach Loops
A foreach loop runs the same block of code for every item in a List.
foreach $list as $item {
// $item = the value of the current cycle of the loop
}
Example:
$colors = ['Red', 'Blue', 'Yellow']
foreach $colors as $color {
print($color ~ ' is a primary color.')
}
//= 'Red is a primary color'
//= 'Blue is a primary color'
//= 'Yellow is a primary color'
Looping Over a Range
Use the range function to loop over a range of numbers.
foreach range(1, 3) as $n {
print($n)
}
//= 1
//= 2
//= 3
You can give a step as the third parameter, to make the loop increment by that value.
// step = 2
foreach range(1, 10, 2) as $n {
print($n)
}
//= 2
//= 4
//= 6
//= 8
//= 10
Looping Over Keys
You can also loop over the key/value pairs of a Map.
Use a slash / to define separate variables for the current key and value.
foreach $map as $key/$value {
...
}
Example:
$countryCodes = {
MX: 'Mexico'
FI: 'Finland'
JP: 'Japan'
}
foreach $countryCodes as $code/$name {
print($code ~ ' is the code for ' ~ $name)
}
//= MX is the code for Mexico
//= FI is the code for Finland
//= JP is the code for Japan
List Indexes
You can also use this approach to loop over List indexes.
$letters = ['A', 'B', 'C']
foreach $letters as $i/$letter {
print($i ~ ' --> ' ~ $letter)
}
//= 1 --> A
//= 2 --> B
//= 3 --> C
Loop Control
break Statement
Use break to immediately exit a loop.
The program will jump to the end of the block and continue from there.
$lines = File.read('quotes.txt')
// Find the 1st quote that refers to 'inspiration'
foreach $lines as $line {
if $line.contains('inspiration') {
print($line)
break // end the loop
}
}
continue Statement
Use continue to skip the current cycle of a loop.
It will immediately jump to the top of the block and resume the next cycle.
$lines = File.read('quotes.txt')
// Print all lines, but skip any that refer
// to 'laziness'
foreach $lines as $line {
if $line.contains('laziness') {
continue // skip to the next cycle
}
print($line)
}
Infinite Loops
The loop statement will keep repeating until you exit via break.
This is useful when you don’t know exactly how many times it should repeat.
loop {
$quote = getNextQuote()
if !$quote {
break
}
else if $quote.contains('creativity') {
print($quote)
}
}
while and do/while commands. THT's flatter approach avoids some common pitfalls with those commands, such as off-by-one bugs.