foreach
foreach ($array as var $value) runs the body once for each element. $value is the element for
that pass.
foreach
foreach visits every element of an array, a generator or any object you can iterate. Write foreach ($subject as var $value), and the body runs once for each element.
var gives the variable the type of the values in $subject. You may get the key too, with var $key => var $value. An array's key is a string, and a Core\ObjectMap's key has the map's key type. You can write the type in place of var, as in string $key => int $value. A loop variable without var and without a type does not compile.
The value variable is a copy. With inout, as in foreach ($rows as inout var $row), each write to the variable goes back into the array. The syntax &$value does not compile. A loop visits the elements the array had when it began, so adding or removing elements does not change what it visits. If the body removes an element and then writes its inout variable, the write throws a LogicError.
The examples below show values, keys with values and inout. Then come a loop over what a function returns, a generator, a wider type, and two loops that do not compile.
Adding up the values of an array
<?nvs// Shows the simplest `foreach`. The body runs once for each element of the array.
var $lineTotals = ['shirt' => 1990, 'socks' => 450, 'belt' => 2500];var $sum = 0;
// `var $cents` gets the type of the array's values, so `$cents` is an `int`.foreach ($lineTotals as var $cents) { $sum = $sum + $cents;}
// This prints 4940. Prices here are in cents.echo $sum, "\n";
// The array can also be written in the loop header. All its values are strings,// so `$tag` is a `string`.foreach (['new', 'sale', 'last one'] as var $tag) { echo '[', $tag, '] ';}echo "\n";
// You can write the type in place of `var`. The compiler checks that the array// contains that type, and the reader sees the type in the loop header.int $largest = 0;foreach ($lineTotals as int $cents) { if ($cents > $largest) { $largest = $cents; }}
// This prints 2500.echo $largest, "\n";4940[new] [sale] [last one]2500Reading the key with the value
<?nvs// Shows the key form of `foreach`. Write `$key => $value` to get both. With `var`,// the key is a `string` and the value has the type of the array's values.
var $stock = ['shirt' => 4, 'socks' => 0, 'belt' => 12];
foreach ($stock as var $item => var $left) { if ($left == 0) { echo $item, ": out of stock\n"; } else { echo $item, ': ', $left, " left\n"; }}
// You can write both types instead. An array key is always a `string`, even when// it looks like a number.array<string> $byId = ['1' => 'Ada', '2' => 'Grace'];foreach ($byId as string $id => string $name) { // This prints: id 1 is Ada, then id 2 is Grace. echo 'id ', $id, ' is ', $name, "\n";}shirt: 4 leftsocks: out of stockbelt: 12 leftid 1 is Adaid 2 is GraceCorrecting every row in place
<?nvs// Shows `inout`, which writes the value back into the array. A program does// this to clean up a table of input before it stores or sends the table.
var $form = [ 'name' => ' Ada Lovelace ', 'city' => 'London ', 'note' => '',];
// `inout var $field` is a `string`, because every value in `$form` is a string.foreach ($form as inout var $field) { $field = Core\Str::trim($field);}
// This prints: {"name":"Ada Lovelace","city":"London","note":""}echo Core\Json::encode($form), "\n";
// This loop writes the type `int` in place of `var`. Without `inout`, the// variable is a copy, and the array keeps its values.array<int> $counts = ['a' => 1, 'b' => 2];foreach ($counts as int $copy) { $copy = $copy * 100;}// This prints: {"a":1,"b":2}echo Core\Json::encode($counts), "\n";{"name":"Ada Lovelace","city":"London","note":""}{"a":1,"b":2}Walking what a function returns
<?nvs// Shows `var` over the result of a function call. The loop variable gets its type// from the function, so the type is not written anywhere in this file.
var $order = "2 x coffee\n1 x filter\n\n3 x mug\n";var $count = 0;
// `Core\Str::lines` returns an array of strings, so `$line` is a `string`.foreach (Core\Str::lines($order) as var $line) { if (Core\Str::isEmpty($line)) { continue; } $count++; echo $count, '. ', $line, "\n";}
// The empty line is skipped, so this prints 3.echo $count, "\n";1. 2 x coffee2. 1 x filter3. 3 x mug3Walking a generator
<?nvs// Shows `foreach` over a generator. The function returns an `Iterator<int>`,// so `$page` is an `int`. A generator has no keys.
class Pages{ // Gives the numbers from 1 to `$last`, one at a time. public static function upTo(int $last): Iterator<int> { int $page = 1; while ($page <= $last) { yield $page; $page++; } }}
foreach (Pages::upTo(3) as int $page) { echo 'page ', $page, "\n";}page 1page 2page 3A wider type and a converted subject
<?nvs// Shows a loop variable with a wider type than the array, and a subject that// is converted in the header.
var $prices = ['apple' => 3, 'pear' => 8];
// The values are `int`, but the body stores a `float` in `$amount`.// So the variable needs the type `int|float`.foreach ($prices as string $name => int|float $amount) { if ($amount > 6) { $amount = $amount * 0.25; } // This prints apple=3, then pear=2. echo $name, '=', $amount, "\n";}
// `$data` is `mixed`, so the loop converts it first. The conversion needs// parentheses, because `as` also separates the subject from the variable.mixed $data = [7, 8];foreach (($data as array<int>) as var $n) { echo $n, "\n";}apple=3pear=278The variable needs a type
<?nvs// Shows that a `foreach` variable needs its type or `var`. `$score` has// neither, so this program does not compile.// proof: compile-error
array<int> $scores = [3, 5];
foreach ($scores as $score) { echo $score, "\n";}error[E0101]: expected a `foreach` binding's type, or `var` --> 07-the-variable-needs-a-type.nvs:8:21 |8 | foreach ($scores as $score) { | ^ write the variable's type, or write `var` to use the element type
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.An array of mixed types
<?nvs// Shows that `var` needs one element type. This array has an `int` and a// `string`, so this program does not compile.// proof: compile-error
foreach ([1, 'two'] as var $item) { echo $item, "\n";}error[E0414]: `var` cannot infer an array whose elements have different types --> 08-an-array-of-mixed-types.nvs:6:10 |6 | foreach ([1, 'two'] as var $item) { | ^^^^^^^^^^ the elements are `int` and `string` = help: put the array in a typed local first, `array<int|string> $items = [1, 'two'];`, and loop over `$items`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
One header can use var for one variable and a written type for the other. A variable without either is the error E0101.
var on the value keeps every qualifier of the element type. Over an array<tainted string>, the value variable is a tainted string.
A written type can be wider than the element type. Write int|float $v over an array<int> if the body stores a float in $v. The compiler checks that each element fits the written type.
A generator, an Iterator<T> and an Iterable<T> give values of type T and have no key. A key variable over one of them is the error E0444. A KeyedIterable<K, V>, such as a Core\ObjectMap, gives keys of type K and values of type V.
The word as in the header belongs to foreach. To convert the subject, put the conversion in parentheses: foreach (($m as array<int>) as var $v). A mixed subject without a conversion is the error E0443.
An array literal can be the subject when the value variable uses var. All its elements need the same type. Elements of different types are the error E0414, and so is an empty array []. With a written type, an array literal does not compile. Put it in a typed variable first.
An inout loop also visits only the elements the array had when it began. An element that the body adds is not visited.
A later foreach in the same function can declare the same variable again with the same type. With another type, the second declaration is the error E0406.
What foreach walks
foreach is the loop over a collection of values. It gives you one value at a time.
It can loop over an array, an object whose class implements Iterable, and an object whose class implements Iterator. A method that contains yield is a generator. It returns an Iterator, so foreach can loop over its result too. Write var for the loop variable, and it gets the type of the values. You can also write the type, and the compiler checks it.
Over an array the loop may get the key as well as the value. An Iterable or an Iterator has no keys, so a loop over one gets the value alone. A class that implements KeyedIterable or KeyedIterator gives a key with each value, as Core\ObjectMap does.
Good to know: a method that takes Iterable<T> as a parameter type works with every class that foreach can loop over. One function can then read a list, a cart or a database result the same way.
The examples below show an array with and without its keys, an object and a generator, a checkout that adds up a shopping cart, and a second loop over one iterator.
Walking an array with and without its keys
<?nvs// Shows the two ways a `foreach` loop walks an array: the values alone, and the keys// together with the values.
var $scores = ['ada' => 31, 'bob' => 27, 'cleo' => 44];
// The loop gives one value per step. `var $score` gets the type of the values, `int`.var $total = 0;foreach ($scores as var $score) { $total = $total + $score;}// This prints 102.echo $total, "\n";
// An array also has keys. `string $name => int $score` gets both, and writes their types.foreach ($scores as string $name => int $score) { echo $name, ' scored ', $score, "\n";}102ada scored 31bob scored 27cleo scored 44Walking an object and an iterator
<?nvs// Shows the other two subjects a `foreach` loop accepts: an object whose class// implements `Iterable`, and an `Iterator` returned by a method that contains `yield`.
class Weekdays implements Iterable<string>{ // `foreach` calls `iterate()` once and walks the iterator it returns. public function iterate(): Iterator<string> { yield 'Monday'; yield 'Tuesday'; yield 'Wednesday'; }}
class Steps{ // A method with `yield` returns an `Iterator`, which `foreach` walks directly. public static function upTo(int $last): Iterator<int> { int $i = 1; while ($i <= $last) { yield $i; $i = $i + 1; } }}
// The subject is an object. `Weekdays` is an `Iterable<string>`, so `$day` is a// `string`. This prints the three names.foreach (new Weekdays() as var $day) { echo $day, "\n";}
// The subject is an iterator. This loop writes the type `int` in place of `var`.// This prints 1, 2 and 3.foreach (Steps::upTo(3) as int $n) { echo $n, "\n";}MondayTuesdayWednesday123Adding up a shopping cart
<?nvs// Shows one method that adds up a shopping cart. Its parameter type is `Iterable<Item>`,// so it walks any class that can be walked and never needs to know how the cart stores// its items.
class Item{ public function constructor( public string $name, public int $cents, public int $quantity, ) {}}
class Cart implements Iterable<Item>{ private array<Item> $items = [];
public function add(Item $item): void { $this->items[] = $item; }
public function iterate(): Iterator<Item> { // `var $item` is an `Item`, because `$this->items` is an `array<Item>`. foreach ($this->items as var $item) { yield $item; } }}
class Checkout{ public static function total(Iterable<Item> $items): int { int $cents = 0; foreach ($items as Item $item) { $cents = $cents + $item->cents * $item->quantity; } return $cents; }}
var $cart = new Cart();$cart->add(new Item('Coffee', 749, 2));$cart->add(new Item('Filter', 399, 1));
// This prints 1897, the price of the whole cart in cents.echo Checkout::total($cart), "\n";1897An iterator continues where it stopped
<?nvs// Shows that a second loop over the same `Iterator` starts where the first// loop stopped. A loop over an `Iterable` starts again from the first value.
class Queue implements Iterable<string>{ public function iterate(): Iterator<string> { yield 'first'; yield 'second'; yield 'third'; }}
Queue $queue = new Queue();Iterator<string> $jobs = $queue->iterate();
// The first loop stops after one value. This prints `first`.foreach ($jobs as string $job) { echo $job, "\n"; break;}
// The same iterator gives the values that are left. This prints `second` and `third`.foreach ($jobs as string $job) { echo $job, "\n";}
// The object calls `iterate()` again for a new loop. This prints `first`.foreach ($queue as string $job) { echo $job, "\n"; break;}firstsecondthirdfirstDetails
The key of an array is always a string, also when the array was written as a list. var $k is a string, and int $k is the error E0723. Convert the key in the loop body if you need a number.
A written value type is checked against the element type. string $v over an array<int> is the error E0401. This is the same over an Iterable<int> and an Iterator<int>.
Any other subject is the error E0443. That covers an object whose class implements neither interface, an int, a string and a ?array<int>. Check a nullable array for null before the loop.
A loop over an Iterator walks the iterator itself. A second loop over the same iterator starts where the first one stopped. After a complete loop, the second loop gets no values. After a break, the second loop gets the values that are left.
Iterators and generators shows how to write a class that
foreach can walk.
Core collections
A foreach loop walks a Core collection the same way it walks an array.
Four classes work this way. Core\ObjectSet gives you its elements in the order you added them. Core\ObjectMap gives you its keys in the same order. Write foreach ($map as var $key => var $value) to get each key with its value. Core\Heap is a collection that sorts its elements. It gives you its elements smallest first, and they stay in the heap. Core\Task\Channel is a queue between two tasks. It gives you each value the other task sent, and the loop ends when that task calls close.
A set, a map and a heap take a copy of their contents when the loop starts. The loop walks that copy, so your code may add or remove elements inside the loop body. The loop still visits what was there at the start, and your changes are in the collection when it ends.
The examples below show a set and a map first, then a heap, then a channel between two tasks.
Walking a set and a map
<?nvs// Shows how to walk a `Core\ObjectSet` and a `Core\ObjectMap` with `foreach`.
var $tags = new Core\ObjectSet<string>();$tags->add('blue');$tags->add('green');$tags->add('blue');
// A set holds each value once, so "blue" is in it once. The loop gives you the// members in the order you added them. This prints blue and then green.foreach ($tags as string $tag) { echo $tag, "\n";}
var $stock = new Core\ObjectMap<string, int>();$stock->set('apples', 12);$stock->set('pears', 4);
// A loop over a map gives you the keys. Use `get` to read the value for a key.foreach ($stock as string $name) { echo $name, ' ', $stock->get($name), "\n";}bluegreenapples 12pears 4Reading a heap without emptying it
<?nvs// Shows how to read every element of a `Core\Heap` in priority order.
var $costs = new Core\Heap<int>();$costs->push(30);$costs->push(5);$costs->push(17);
// The loop gives you the elements smallest first. This prints 5, 17 and 30.foreach ($costs as int $cost) { echo $cost, "\n";}
// The loop takes nothing out of the heap. All three elements are still there,// so this prints 3.echo $costs->count(), "\n";
// `pop` is what removes one. This prints 5, the same element the loop saw first.echo $costs->pop(), "\n";5173035A worker task reading its jobs
<?nvs// Shows a worker task taking its jobs from a `Core\Task\Channel` with `foreach`.
class Report{ public static string $done = '';}
// The channel holds 2 jobs at a time. A sender waits while it is full, so a fast// sender cannot fill up the memory of a slow worker.var $jobs = new Core\Task\Channel<string>(2);
Core\Task::all({ fill: fn(): int => { array<string> $queue = ['resize-logo', 'resize-banner', 'resize-icon']; foreach ($queue as string $job) { $jobs->send($job); } // `close` ends the loop in the other task. Without it, that loop waits forever. $jobs->close(); return 0; }, work: fn(): int => { // The loop gives you each job that was sent, in the order it was sent. foreach ($jobs as string $job) { Report::$done = Report::$done . $job . ' '; } return 0; },});
// Both tasks have finished here, so this prints all three job names.echo Report::$done, "\n";resize-logo resize-banner resize-iconDetails
Core\ObjectSet<T>, Core\Heap<T> and Core\Task\Channel<T> are each an Iterable<T>. Core\ObjectMap<K, V> is an Iterable<K> and a KeyedIterable<K, V>. You can pass each collection to a parameter with one of its types.
A loop with only a value variable over a map gives the keys. A loop with a key variable gives each key with its value. Over an ObjectMap<Tag, int>, foreach ($map as var $tag => var $n) gives $tag the type Tag and $n the type int. If you write a type for a variable and it does not fit, the error is E0401. A set, a heap and a channel have no keys, so a key variable over one is the error E0444.
A heap made with a compare function gives its elements in the order that function sets. A heap of Comparable objects gives them in the order of compareTo.
A set, a map and a heap can be walked many times, and each loop gives every element again.
A loop over a channel takes each value out of it, so a second loop over the same closed channel gets no values. The first loop also gets the values that were sent before close.
Keys and values from a map
A foreach loop over a Core\ObjectMap can give you each key with its value. Write foreach ($map as var $key => var $value). $key gets the map's key type, and $value gets its value type.
The loop gives the entries in the order you added them. It walks the map as it was when the loop started. If the loop body adds an entry, the loop does not visit it. If the body removes an entry, the loop still visits it, with its old value. When the loop ends, the map has every change the body made.
A class of your own can give keys and values too. It implements KeyedIterable<K, V>, and its iterateKeyed method returns a KeyedIterator<K, V>. A loop with one variable over a map gives only the keys.
The examples below show a loop with written types, then a loop with var, then a class of your own.
Each key with its value
<?nvs// Shows a `foreach` loop that gives each key of a `Core\ObjectMap` with its value.
final class Tag{ public string $name;
public function constructor(string $name) { $this->name = $name; }}
Core\ObjectMap<Tag, int> $stock = new Core\ObjectMap<Tag, int>();$stock->set(new Tag('shirts'), 14);$stock->set(new Tag('hats'), 3);$stock->set(new Tag('scarves'), 8);
// Each step gives one tag and its stock count. This prints `shirts: 14`,// then `hats: 3`, then `scarves: 8`.int $total = 0;foreach ($stock as Tag $tag => int $count) { echo $tag->name, ': ', $count, "\n"; $total = $total + $count;}
// This prints `total: 25`.echo 'total: ', $total, "\n";shirts: 14hats: 3scarves: 8total: 25Var takes the types from the map
<?nvs// Shows `var` in a keyed `foreach` loop, where each variable gets its type from the map.
final class Product{ public string $name; public int $priceInCents;
public function constructor(string $name, int $priceInCents) { $this->name = $name; $this->priceInCents = $priceInCents; }
public function label(): string { return Core\Str::upper($this->name); }}
var $cart = new Core\ObjectMap<Product, int>();$cart->set(new Product('coffee', 450), 2);$cart->set(new Product('bagel', 300), 3);
// `$product` is a `Product`, so it has the `label` method and the price property.// `$quantity` is an `int`. This prints `COFFEE 2 x 450 = 900`, then `BAGEL 3 x 300 = 900`.foreach ($cart as var $product => var $quantity) { int $line = $product->priceInCents * $quantity; echo $product->label(), ' ', $quantity, ' x ', $product->priceInCents, ' = ', $line, "\n";}COFFEE 2 x 450 = 900BAGEL 3 x 300 = 900A class of your own with keys and values
<?nvs// Shows a class of your own that gives keys and values to a `foreach` loop.
final class ScoreCursor implements KeyedIterator<string, int>{ private array<string> $players; private array<int> $scores; private int $at = -1;
public function constructor(array<string> $players, array<int> $scores) { $this->players = $players; $this->scores = $scores; }
// `advance` moves to the next entry. It returns `false` when there are no more entries. public function advance(): bool { $this->at = $this->at + 1; return $this->at < Core\Arr::count($this->players); }
public function key(): string { return $this->players[$this->at]; }
public function current(): int { return $this->scores[$this->at]; }}
final class Scoreboard implements KeyedIterable<string, int>{ private array<string> $players = []; private array<int> $scores = [];
public function add(string $player, int $score): void { $this->players[] = $player; $this->scores[] = $score; }
// Each loop calls `iterateKeyed` and gets a new cursor that starts at the first entry. public function iterateKeyed(): KeyedIterator<string, int> { return new ScoreCursor($this->players, $this->scores); }}
var $board = new Scoreboard();$board->add('Ana', 120);$board->add('Ben', 95);$board->add('Chloe', 140);
// The loop gives each player with a score. This prints `Ana: 120`, `Ben: 95` and `Chloe: 140`.foreach ($board as var $player => var $score) { echo $player, ': ', $score, "\n";}Ana: 120Ben: 95Chloe: 140Details
A written key type must accept the map's key type. A wider type, such as object, is allowed. Any other type is the error E0401. The same is true for the value.
A key can be tainted (it may come from outside the program). Then var $key is tainted too. A plain string $key over a tainted string key is the error E0851. A tainted value comes from outside, so it cannot go into a plain string.
A key variable over an Iterable or an Iterator is the error E0444. These interfaces give values and no keys.
inout on the value is the error E0490. To change a value, call $map->set($key, $newValue).
[] does not work on a Core\ObjectMap. Read a value with get and write one with set.
Core\Arr::from
Core\Arr::from turns a sequence into a plain array.
It takes whatever a foreach loop takes: an array, a generator, an object you can walk, or a Core collection. The result is an array<T> numbered from 0, holding the values in the order the sequence gave them. Use it when you need the whole sequence at once, to count it, to sort it, or to read it more than once. A generator is walked once and is then spent, so keep the array you get back.
Good to know: the limit option stops the walk after the number of values you name. A sequence with no end needs it, or the call never returns.
The examples below show a generator collected into an array, then limit on a sequence with no end, then a Core collection sorted.
A generator as an array
<?nvs// Shows how to collect the values of a generator into a plain array.
class Fibonacci{ public static function first(int $many): Iterator<int> { int $a = 1; int $b = 1; int $n = 0; while ($n < $many) { yield $a; int $next = $a + $b; $a = $b; $b = $next; $n = $n + 1; } }}
// `Core\Arr::from` walks the generator to its end and keeps every value.array<int> $numbers = Core\Arr::from(Fibonacci::first(7));
// The keys start at 0. This prints 7, then 13.echo Core\Arr::count($numbers), "\n";echo $numbers[6], "\n";
// The values are in an array now, so you can read them as often as you like.// This prints 33.echo Core\Arr::sum($numbers), "\n";71333Taking the first few values
<?nvs// Shows the `limit` option, which stops the walk after the number of values you name.
class Ids{ // This generator has no end. public static function forever(string $prefix): Iterator<string> { int $n = 1; while (true) { yield "{$prefix}-{$n}"; $n = $n + 1; } }}
// `limit` is what makes this call return. It stops the walk after three values.array<string> $batch = Core\Arr::from(Ids::forever('order'), { limit: 3 });
// This prints order-1, order-2 and order-3.foreach ($batch as string $id) { echo $id, "\n";}order-1order-2order-3Sorting what a collection holds
<?nvs// Shows how to take a `Core` collection into an array and sort it. A program does this// when it gathers values while it works and puts them in order at the end.
var $seen = new Core\ObjectSet<string>();$seen->add('marta');$seen->add('ada');$seen->add('kofi');$seen->add('ada');
// A set gives its members in the order you added them, and keeps each one once.// This prints 3.array<string> $names = Core\Arr::from($seen);echo Core\Arr::count($names), "\n";
// `Core\Arr::sort` needs every value at once, which is why the array above is made// first. This prints ada, kofi and marta.foreach (Core\Arr::sort($names) as string $name) { echo $name, "\n";}3adakofimartaDetails
The element type of the result is the element type of the sequence. A generator of int gives an array<int>, and a Core\ObjectMap<string, int> gives an array<string>. Assigning the result to another array type is the error E0401.
An array literal written in the call gives an array<mixed>. array<int> $b = Core\Arr::from([1, 2, 3]); is the error E0401. Put the array in a typed variable first.
The keys of an array are not kept. An array with the keys "x" and "y" gives an array with the keys 0 and 1.
The argument must be an array, an Iterable<T>, an Iterator<T> or a Core collection. Any other type is the error E0401, and this is true for mixed too.
limit is a uint. A negative number or a string is the error E0401. limit: 0 gives an empty array, and the body of a generator does not run. A limit larger than the sequence gives the whole sequence. Any other option name is the error E0454.
With limit, a generator stops where the limit is reached. A later loop or a later Core\Arr::from over the same generator continues with the next value.
A heap is not emptied. Core\Arr::from gives its elements in priority order, and the heap still has them all.
An error thrown by a generator reaches the code that called Core\Arr::from.
Use this when you need the position as a number
Section titled “Use this when you need the position as a number”The key of an array in foreach is a string, so you cannot do arithmetic with it. When you need the
position as an int, use a for loop.
Do and don’t
Section titled “Do and don’t”- Do use
varfor the loop variable unless you need a wider type. - Do use
inoutto change the elements of an array in place. - Don’t add elements to the array inside the loop and expect the loop to visit them.
- Don’t write a key variable over an
Iterableor anIterator. A key works over an array and over aKeyedIterable, such as aCore\ObjectMap. Iterators and generators explainsKeyedIterable.
