while and for
while (condition) runs its body again and again while the condition is true. for counts: it
runs a start once, then the body while a condition is true, and a step after each pass.
while and do while
while (condition) { … } runs its body again and again for as long as the condition is true. The condition is tested first, so a condition that is false at the start means the body never runs.
do { … } while (condition); runs the body first and tests the condition afterwards. The body therefore always runs at least once. Note the semicolon after the closing bracket.
break leaves the loop. continue skips the rest of the body and goes to the next test. In a do … while loop, continue goes to the test at the bottom, and does not restart the body.
The condition is read the same way an if condition is. It does not have to be a bool.
Use while when you do not know how many rounds you need, such as reading until nothing is left. Use a for or a foreach loop when you are counting or walking a collection.
The examples below show a while loop that drains a queue of work, then a do … while loop that always runs once, then a retry that stops on success or after a limit.
Working through a list until it is empty
<?nvs// Shows a `while` loop. The condition is tested before every round, including// the first one, so a list that is already empty means no round at all.
class Queue{ public static function drain(array<string> $jobs): int { int $done = 0; int $at = 0; while ($at < Core\Arr::count($jobs)) { echo 'running ', $jobs[$at as string], "\n"; $done = $done + 1; $at = $at + 1; } return $done; }}
array<string> $jobs = ['backup', 'send mail', 'clean up'];// This prints one line per job, then 3.echo Queue::drain($jobs), "\n";
array<string> $none = [];// This prints 0. The condition was false at the start, so the body never ran.echo Queue::drain($none), "\n";running backuprunning send mailrunning clean up30Asking once before testing anything
<?nvs// Shows `do … while`. The body runs before the condition is tested, so it// always runs at least once. Note the semicolon after the closing bracket.
// A page of results is fetched, and another page only while a full one came// back. The first page is always fetched.class Pages{ public static function sizeOf(int $page): int { if ($page < 3) { return 100; } return 12; }}
int $page = 1;int $rows = 0;int $size = 0;do { $size = Pages::sizeOf($page); $rows = $rows + $size; echo 'page ', $page, ' gave ', $size, " rows\n"; $page = $page + 1;} while ($size == 100);
// This prints 212.echo $rows, "\n";
// The same loop written with `while` would fetch nothing here, because the// condition is false from the start.int $count = 0;do { $count = $count + 1;} while (false);// This prints 1.echo $count, "\n";page 1 gave 100 rowspage 2 gave 100 rowspage 3 gave 12 rows2121Trying again until it works or the limit is reached
<?nvs// Shows a `while` loop with two ways to end: the work succeeded, or the limit// was reached. A program does this around a call that sometimes fails.
class Upload{ // Fails on the first two attempts and succeeds on the third. public static function send(int $attempt): bool { return $attempt >= 3; }}
int $attempt = 0;bool $sent = false;
while ($sent == false && $attempt < 5) { $attempt = $attempt + 1; $sent = Upload::send($attempt); if ($sent) { echo 'sent on attempt ', $attempt, "\n"; } else { echo 'attempt ', $attempt, " failed\n"; }}
if ($sent == false) { echo 'gave up after ', $attempt, " attempts\n";}
// This prints 3.echo $attempt, "\n";attempt 1 failedattempt 2 failedsent on attempt 33for
A for loop counts. Its header has three parts, separated by semicolons: where the counter starts, how long the loop runs, and how the counter changes after every round. for (var $i = 0; $i < 10; $i++) runs the body while $i is below 10.
The first part is either one new variable, or assignments to variables declared above the loop. The second and third parts may each be a list separated by commas. Any part may be empty, and for (;;) runs until a break.
The counter belongs to the function, not to the loop. After the loop, it has the value that ended it. A second loop in the same function needs a different name. continue runs the third part before the next test.
The examples below show a var counter, two counters that meet in the middle, uint counters, a for (;;) loop, and a header that does not compile.
Numbering every line of a list
<?nvs// Shows the three parts of a `for` header: where the counter starts, how long// the loop runs, and how the counter changes after every round.
var $steps = ['unpack the archive', 'check the files', 'install'];
// `var $i = 0` declares the counter. It is an `int`, the type of `0`.for (var $i = 0; $i < Core\Arr::count($steps); $i++) { // The counter is also the position in the array. echo $i + 1, '. ', $steps[$i], "\n";}
// You can read the counter after the loop. It holds the value that ended the// loop, so this prints 3.echo $i, "\n";1. unpack the archive2. check the files3. install3Walking a list from both ends
<?nvs// Shows a loop with two counters. The first and the third part of the header// are lists separated by commas, so both counters start and move together.
array<string> $names = ['Ada', 'Grace', 'Alan', 'Edsger'];
uint $front = 0;uint $back = 0;
for ($front = 0, $back = Core\Arr::count($names) - 1; $front < $back; $front++, $back--) { string $keep = $names[$front]; $names[$front] = $names[$back]; $names[$back] = $keep;}
// The counters meet in the middle, and every pair has changed places. This// prints ["Edsger","Alan","Grace","Ada"].echo Core\Json::encode($names), "\n";["Edsger","Alan","Grace","Ada"]Sending rows in batches
<?nvs// Shows a counter that moves by more than one. A program does this to send a// long list in batches, because one request per row would be too many requests.
class Store{ // Writes one batch and returns how many rows it held. public static function write(array<int> $rows): uint { echo 'writing ', Core\Json::encode($rows), "\n"; return Core\Arr::count($rows); }}
array<int> $ids = [11, 12, 13, 14, 15, 16, 17];uint $total = Core\Arr::count($ids);uint $written = 0;
// The counters write their type, `uint`, in place of `var`. A `uint` is never// negative, and neither is a position in a list.for (uint $start = 0; $start < $total; $start = $start + 3) { array<int> $batch = []; // The inner loop stops at the end of the batch or at the end of the list, // whichever comes first. for (uint $at = $start; $at < $start + 3 && $at < $total; $at++) { $batch[] = $ids[$at]; } $written = $written + Store::write($batch);}
// Seven rows do not divide into batches of three, so the last batch is// shorter. This prints 7.echo $written, "\n";writing [11,12,13]writing [14,15,16]writing [17]7A loop that ends with break
<?nvs// Shows a `for` loop with an empty header. `for (;;)` has no test, so only// `break` ends it.
int $tries = 0;
for (;;) { $tries++; echo 'try ', $tries, "\n"; if ($tries == 3) { break; }}
// The loop ran three times. This prints 3.echo $tries, "\n";try 1try 2try 33The header declares one variable
<?nvs// Shows that the first part of a `for` header declares one variable at most.// This header declares two, so this program does not compile.// proof: compile-error
for (int $row = 0, int $column = 0; $row < 3; $row++) { echo $row, "\n";}error[E0125]: a `for` init clause declares at most one binding --> 05-the-header-declares-one-variable.nvs:6:20 |6 | for (int $row = 0, int $column = 0; $row < 3; $row++) { | ^^^^^^^^^^^^^^^ this is the second declaration = help: declare the second variable above the loop. The variable can be used in the whole function either way
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
The first part of the header declares one variable at most. for (int $a = 0, int $b = 0; …) is the error E0125. Declare the second variable above the loop.
The first part is either one declaration or a list of expressions. It cannot have both. for (var $i = 0, $j = 1; …) is the error E0124.
The second part can be a list separated by commas. Before each test, the loop runs every expression in the list. The last expression decides if the loop runs again. The expressions before it also run on the test that ends the loop.
Two loops in one function cannot declare the same counter. The second declaration is the error E0406.
Use this when you loop over an array
Section titled “Use this when you loop over an array”To visit each element of an array, foreach is shorter. It needs
no counter.
Do and don’t
Section titled “Do and don’t”- Do use
whilewhen you do not know how many passes the loop needs. - Do use
forwhen you count. - Don’t declare two variables in the start of a
for. Declare the second one before the loop. - Don’t use the same counter name in two
forloops of one function.
