Skip to content

break, continue and return

break and continue change what a loop does next. return ends a method, or a file at its top level.

break and continue

break stops a loop immediately. continue skips the rest of the current iteration and starts the next one.

Both act on the loop closest to them. Inside a switch, break leaves the switch, and a plain continue starts the next iteration of the loop around it, because a switch has no iterations of its own.

Write a number after either word to leave more than one level at once. break 2 leaves the loop around the loop you are in. Levels count from 1 at the closest statement, and every loop and every switch is one level. The number has to be written directly in the code, so a variable is not allowed there.

Good to know: a level with no matching loop or switch does not compile. A wrong number is an error you see before the program runs.

The examples below take these in turn: a search that stops at the first match, a loop that skips the rows it does not want, and an order check that leaves two loops at once. The last two show a switch inside a loop, and a continue that does not compile.

Stopping a search at the first match

<?nvs
// Shows how `break` stops a loop as soon as the work is done. This loop looks
// for the first reading above 100 and stops there.
array<int> $readings = [12, 40, 96, 140, 3, 220];
int $found = 0;
foreach ($readings as int $reading) {
if ($reading > 100) {
$found = $reading;
break;
}
echo 'checked ', $reading, "\n";
}
// The loop stopped at 140 and never read the two values after it.
// This prints 140.
echo 'first above 100: ', $found, "\n";
Output
checked 12
checked 40
checked 96
first above 100: 140

Skipping the rows you do not want

<?nvs
// Shows how `continue` skips the rest of one iteration and starts the next
// one. This loop greets every name in the list and skips the empty entries.
array<string> $names = ['Ada', '', 'Grace', ' ', 'Alan'];
int $greeted = 0;
foreach ($names as string $name) {
// `Core\Str::trim` removes the spaces at both ends of the text.
string $clean = Core\Str::trim($name);
if ($clean == '') {
continue;
}
$greeted = $greeted + 1;
echo 'hello ', $clean, "\n";
}
// Two of the five entries were skipped, so this prints 3.
echo $greeted, " greeted\n";
Output
hello Ada
hello Grace
hello Alan
3 greeted

Leaving two loops at once in an order check

<?nvs
// Shows `continue 2` and `break 2`, which act on the second level out. Level 1
// is the inner loop and level 2 is the outer one. A shop checks its orders for
// one product, and an order holding a `pen` is not shipped at all.
class Order
{
public function constructor(public string $id, public array<string> $items)
{}
}
array<Order> $orders = [
new Order('A-1', ['book', 'pen', 'lamp']),
new Order('A-2', ['cup', 'mug']),
new Order('A-3', ['ring', 'box']),
];
string $wanted = 'ring';
string $foundIn = '';
foreach ($orders as Order $order) {
echo 'order ', $order->id, "\n";
foreach ($order->items as string $item) {
if ($item == 'pen') {
// `continue 2` starts the outer loop's next iteration, so the rest
// of this order and the line after the inner loop are both skipped.
echo " holds a pen, skipping this order\n";
continue 2;
}
if ($item == $wanted) {
$foundIn = $order->id;
// `break 2` leaves both loops, so the `box` after it is never read.
break 2;
}
echo ' ', $item, "\n";
}
echo " order checked\n";
}
// This prints A-3.
echo 'found in ', $foundIn, "\n";
Output
order A-1
book
holds a pen, skipping this order
order A-2
cup
mug
order checked
order A-3
found in A-3

A switch inside a loop

<?nvs
// Shows `break` and `continue` inside a `switch` that is inside a loop.
// This log printer skips debug lines and marks errors.
array<string> $levels = ['info', 'debug', 'error', 'info'];
array<string> $messages = ['started', 'cache is warm', 'disk is full', 'stopped'];
for (int $i = 0; $i < 4; $i++) {
switch ($levels[$i]) {
case 'debug':
// `continue` starts the next line, so the `echo` below does not run.
continue;
case 'error':
echo '!! ';
// `break` leaves only the `switch`. The message below is still printed.
break;
default:
echo ' ';
}
echo $messages[$i], "\n";
}
Output
started
!! disk is full
stopped

Continue needs a loop

<?nvs
// Shows that `continue` needs a loop around it. A `switch` alone is not
// enough, so this program does not compile.
// proof: compile-error
string $command = 'skip';
switch ($command) {
case 'skip':
continue;
}
Output
error[E0475]: `continue` is not inside a loop
--> 05-continue-needs-a-loop.nvs:10:9
|
10 | continue;
| ^^^^^^^^^ no enclosing loop to leave
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

Inside a switch that is inside a loop, continue, continue 1 and continue 2 do the same thing. Each one starts the next iteration of the loop.

break 1 is the same as break, and continue 1 is the same as continue. The smallest level is 1, so break 0 does not compile.

These programs do not compile, because no statement matches the level:

  • break or continue outside any loop or switch.
  • continue inside a switch with no loop around it.
  • break 3 inside only one loop.

return

return $value; leaves the method it is in and gives the value to whoever called the method. The lines after it do not run, and neither does the rest of any loop it is inside. A method may have as many return statements as you need, and the first one that runs ends the method.

The value has to fit the return type the method declares. A method declared void gives nothing back, so its return carries no value and is written return; alone. Writing a value there does not compile.

return also works outside any method, at the top level of a file. There it ends the file. In the file you started, that ends the program.

The examples below show a method that returns as soon as it has found what it was looking for, then a void method that ends early, then a program that stops because it has nothing to do. The last one shows a void method with a value in its return, which does not compile.

Giving a value back to the caller

<?nvs
// Shows `return`, which leaves a method and gives a value back to the caller.
// The first `return` that runs ends the method, so the loop stops there.
class Basket
{
// Gives the first price over the limit, or 0 when there is none.
public static function firstOver(array<int> $prices, int $limit): int
{
foreach ($prices as int $price) {
if ($price > $limit) {
return $price;
}
}
return 0;
}
}
array<int> $prices = [300, 1200, 4500];
// This prints 1200. The method ends at the first price over 1000, so 4500 is
// never looked at.
echo Basket::firstOver($prices, 1000), "\n";
// This prints 0. No price is over 9000, so the last line of the method runs.
echo Basket::firstOver($prices, 9000), "\n";
Output
1200
0

Leaving a method that has no value

<?nvs
// Shows `return;` with no value. A `void` method gives nothing back, so its
// `return` carries no value, and it is how such a method ends early.
class Mailer
{
public static function send(string $address, string $text): void
{
if ($address == '') {
echo "no address, nothing sent\n";
return;
}
echo 'sent to ', $address, ': ', $text, "\n";
}
}
// The first call ends at the `return`, so it prints one line about the missing
// address. The second call prints the message it sent.
Mailer::send('', 'your order is on its way');
Mailer::send('ada@example.com', 'your order is on its way');
Output
no address, nothing sent
sent to ada@example.com: your order is on its way

Ending a program that has nothing to do

<?nvs
// Shows `return` outside any method, which ends the file. In the file you
// started, that ends the program. A script does this when it has no work.
array<string> $jobs = [];
if (Core\Arr::count($jobs) == 0) {
echo "nothing to do\n";
return;
}
// This line never runs, because the `return` above ended the program.
echo 'running ', Core\Arr::count($jobs), " jobs\n";
Output
nothing to do

A void method cannot return a value

<?nvs
// Shows that a `void` method cannot return a value. This `return` has a
// value, so this program does not compile.
// proof: compile-error
class Counter
{
public static function reset(): void
{
return 0;
}
}
Counter::reset();
Output
error[E0403]: this method declares `void` but returns `int`
--> 04-a-void-method-cannot-return-a-value.nvs:10:16
|
10 | return 0;
| ^ this is `int`
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

A method with a return type other than void needs a value in every return. In such a method, return; alone does not compile.

Every way through such a method has to end with a return or a throw. If one way reaches the end of the method body, the program does not compile.

A file that another file loads with require can end with return $value; at its top level. The require expression then gives that value.

throw also ends a method. The page throw and catch explains it.

break 2 leaves an inner loop and the loop around it at once. When the loops are inside a method, return is often clearer.

  • Do use continue at the top of a loop body to skip values you do not need.
  • Do move nested loops into a method when you need break 3 or more.
  • Don’t use break to leave an if. It ends the loop around the if.
  • Don’t write code after return in the same block. It never runs.