if and else
if (condition) runs its body when the condition is true. elseif tests another condition, and
else runs when no condition before it was true.
if, elseif and else
if runs a block of code when its condition is true. else gives the block that runs when it is not. elseif adds a further condition to test in between. You may write else if instead, and the two are the same.
The arms are tested from top to bottom, and only the first one whose condition is true runs. else comes last and takes everything the arms above it did not.
The condition is any expression, and it does not have to be a bool. The value is read as a condition: 0, 0.0, "", "0", [], null and false count as false, and every other value counts as true.
A body of one statement needs no braces. if ($n > 1) echo "big\n"; is allowed. Braces around every body are still the safer habit.
The examples below show a chain that picks one arm, then conditions that are not bool values, then a shipping price worked out from several rules in order.
Picking one arm of a chain
<?nvs// Shows an `if`/`elseif`/`else` chain. The arms are tested from top to bottom,// and only the first one whose condition is true runs.
class Band{ public static function of(int $score): string { if ($score >= 90) { return 'excellent'; } elseif ($score >= 75) { return 'good'; } elseif ($score >= 50) { return 'pass'; } else { return 'fail'; } }}
array<int> $scores = [95, 80, 60, 20];
foreach ($scores as int $score) { // This prints one line per score: 95 excellent, 80 good, 60 pass, 20 fail. echo $score, ' ', Band::of($score), "\n";}95 excellent80 good60 pass20 failA condition that is not a bool
<?nvs// Shows conditions that are not `bool` values. The value is read as a// condition, so an empty array, an empty string and the number 0 are false.
array<string> $names = [];if ($names) { echo "there are names\n";} else { // This line runs. An empty array counts as false. echo "no names yet\n";}
int $unread = 0;if ($unread) { echo "you have unread messages\n";} else { // This line runs. The number 0 counts as false. echo "your inbox is empty\n";}
// The text "0" counts as false as well. Test the length when you mean// "this text is not empty".string $answer = '0';if ($answer) { echo "the answer counts as true\n";} elseif (Core\Str::length($answer) > 0) { // This line runs. echo "the answer is not empty, and it still counts as false\n";}no names yetyour inbox is emptythe answer is not empty, and it still counts as falseWorking out a shipping price
<?nvs// Shows several rules tested in order, the way a program works out a price.// The first rule that fits decides, so the order of the arms is part of the// rules. Prices here are in cents.
class Shipping{ public static function priceFor(string $country, int $grams, bool $isMember): int { if ($isMember && $grams <= 2000) { return 0; } elseif ($country != 'DE') { return 1490; } elseif ($grams > 10000) { return 990; } elseif ($grams > 2000) { return 590; } return 390; }}
// This prints 0. The member rule is first, so it wins over every rule below it.echo Shipping::priceFor('DE', 800, true), "\n";// This prints 1490. A parcel outside Germany takes the same price at any weight.echo Shipping::priceFor('FR', 800, false), "\n";// This prints 990.echo Shipping::priceFor('DE', 12000, false), "\n";// This prints 390. No arm matched, so the line after the chain decides.echo Shipping::priceFor('DE', 800, false), "\n";01490990390Comparison and logic explains how values are compared in a condition.
Blocks and variables
A statement is one step of a program. Most statements are an expression followed by ;: a call, an assignment, an echo. The value is thrown away, and the work still happens. A ; on its own is an empty statement.
A declaration is a statement too. Write the type, or write var and the type comes from the value. A variable belongs to the whole function, so each name is declared once.
Braces { … } group statements into a block. A block does not open a new scope. You may read a variable only where every path has given it a value. A variable assigned in one branch of an if is readable after the if when every branch assigns it.
The examples below show the statements, a variable declared before its value is known, and a program that prices an order. The last one reads a variable that only one branch declares, and does not compile.
The statements a program is made of
<?nvs// Shows the kinds of statement a program is made of: a declaration, an// assignment, a call written for what it does, and an empty statement.
class Report{ // Prints one line and returns how many characters it printed. public static function line(string $text): uint { echo $text, "\n"; return Core\Str::length($text); }}
// A declaration is a statement. It gives `$total` a type and a first value.int $total = 0;
// An assignment followed by `;` is a statement.$total = $total + 7;
// This call is a statement. The program runs it for what it prints, and the// number it returns is thrown away.Report::line('counted');
// A `;` on its own is an empty statement. It does nothing.;
// This prints 7.echo $total, "\n";counted7Declaring a variable before its value is known
<?nvs// Shows the two ways to declare a variable, and how to declare one before you// know its value.
// A declaration names the type. `$attempts` is a whole number from here on.int $attempts = 3;
// `var` takes the type from the value on the right, so `$service` is a string.var $service = 'payments';
// You can declare a variable without a value. You may read it only after every// path has given it one, so both branches below assign it.string $plan;if ($attempts > 1) { $plan = 'retry';} else { $plan = 'give up';}
// Braces group statements into a block. A block does not open a new scope, so// `$wait` is still there after the closing brace.{ int $wait = $attempts * 2;}
// This prints: payments: retry after 6 secondsecho $service, ': ', $plan, ' after ', $wait, " seconds\n";payments: retry after 6 secondsPricing an order step by step
<?nvs// Shows these statements in a program that prices an order: a variable// declared before its price is known, a call written for what it records, and// a block that groups one step.
class Audit{ // Writes one line about a decision and returns whether it was written. public static function note(string $text): bool { echo 'audit: ', $text, "\n"; return true; }}
array<int> $order = ['items' => 4, 'weight' => 1200];
// The shipping price is not known yet. Every branch below gives it a value, so// it can be read after the `if`.int $shipping;if ($order['weight'] > 1000) { $shipping = 900; // The result of this call is thrown away. The line is still written. Audit::note('heavy parcel');} elseif ($order['items'] > 3) { $shipping = 400; Audit::note('more than three items');} else { $shipping = 250;}
// The block groups the discount step. `$discount` can be read after it,// because a block does not open a new scope.{ int $discount = 0; if ($shipping > 500) { $discount = 100; }}
// This prints 800.echo $shipping - $discount, "\n";audit: heavy parcel800A variable declared in one branch cannot be read after it
<?nvs// Shows that a variable declared in one branch of an `if` cannot be read after// the `if`. When `$flag` is false, `$x` has no value, so this program does not// compile.// proof: compile-error
bool $flag = true;if ($flag) { int $x = 1;}echo $x;error[E0301]: `$x` is read before any assignment reaches it --> 04-a-variable-declared-in-one-branch-cannot-be-read-after-it.nvs:11:6 |11 | echo $x; | ^^ not definitely assigned here
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
A variable is declared once in a function. A second declaration of the same name does not compile: it is the error E0406. This is also true inside a block, and for the variable of a second for loop.
A declaration inside a loop body is one statement. It runs on every round of the loop, and it gives the variable its first value again each time.
A variable declared inside one branch of an if has no value on the other paths. Reading it after the if does not compile: it is the error E0301.
Use this when you choose between values
Section titled “Use this when you choose between values”When each branch only picks a value, match is shorter. It returns
the value, so you assign it once.
Do and don’t
Section titled “Do and don’t”- Do use braces around every body that is longer than one short line.
- Do declare a variable before the
ifwhen both branches set it. - Don’t write
if (...):withendif;. Novis only has the brace syntax. - Don’t declare the same variable again in a second block. Assign it instead.
