Skip to content

Arithmetic and assignment

+, -, *, /, % and ** work on the four number types: int, uint, float and decimal. = and the operators like += store a value in a variable.

Arithmetic

The arithmetic operators + - * / % ** work on the four number types: int, uint, float and decimal.

Both sides must be numbers. "3" * 2 does not compile, so you write ($s as int) * 2. A whole number and a float give a float, so 3 + 0.5 is 3.5. An int and a uint do not mix, and a decimal and a float do not mix either. Dividing two whole numbers gives a whole number when the result is exact. Otherwise it gives a float, so 7 / 2 is 3.5. A result too large for a whole number throws an ArithmeticError. A division by zero, % by zero and a negative power of a whole number throw it too.

Good to know: use decimal for money. A float cannot store 0.1 exactly, so ten additions of 0.1 do not give 1.0. A decimal stores digits, and the total is exact.

The examples below show everyday arithmetic, the errors arithmetic throws and a basket priced in decimal. Then they show an int and a uint in one expression, the operators ++ and --, and the bitwise operators.

Everyday arithmetic on numbers

<?nvs
// Shows the arithmetic operators on whole numbers and on fractions, and what
// dividing two whole numbers gives.
int $apples = 7;
int $baskets = 2;
// Dividing two whole numbers gives a whole number when it comes out even and
// a fraction when it does not. This prints 3.5 and 2.
echo $apples / $baskets, ' ', 6 / 3, "\n";
// For a whole number use `Core\Math::quotient`, which drops the remainder, and
// `%` for the remainder itself. This prints 3 and 1.
echo Core\Math::quotient($apples, $baskets), ' ', $apples % $baskets, "\n";
// `**` raises a number to a power. This prints 1024.
echo 2 ** 10, "\n";
// A fraction on either side makes the result a fraction. This prints 3.75
// and 3.5.
echo 1.5 + 2.25, ' ', 3 + 0.5, "\n";
Output
3.5 2
3 1
1024
3.75 3.5

The errors arithmetic throws

<?nvs
// Shows the errors arithmetic throws instead of giving you a wrong number.
// Each one is an `ArithmeticError` and can be caught.
int $largest = 9223372036854775807;
// A whole number that grows past what it can hold throws. It does not wrap
// around to a negative number.
try {
echo $largest + 1, "\n";
} catch (ArithmeticError $overflow) {
echo $overflow->message, "\n";
}
// Dividing by zero throws, whatever kind of numbers you divide.
try {
echo 1 / 0, "\n";
} catch (ArithmeticError $divide) {
echo $divide->message, "\n";
}
// A negative exponent has no whole-number result, so it throws too.
try {
echo 2 ** -1, "\n";
} catch (ArithmeticError $power) {
echo $power->message, "\n";
}
// `Core\Math::divide` is the division that gives `INF` instead of throwing.
// This prints INF.
echo Core\Math::divide(1.0, 0.0), "\n";
Output
Integer addition overflowed
Division by zero
Negative exponent has no integer result
INF

A basket priced in decimal

<?nvs
// Shows why money is added up in `decimal`. Ten additions of 0.1 as a `float`
// look right and are not, and the same ten in `decimal` are exact.
float $floatTotal = 0.0;
decimal $step = 0.1;
decimal $decimalTotal = 0.0;
int $item = 0;
while ($item < 10) {
$floatTotal = $floatTotal + 0.1;
$decimalTotal = $decimalTotal + $step;
$item = $item + 1;
}
// The `float` total prints as 1 and is still not equal to 1.0, so this prints
// "1 no". The `decimal` total is equal, so the next line prints "1.0 yes".
echo $floatTotal, ' ', $floatTotal == 1.0 ? 'yes' : 'no', "\n";
echo $decimalTotal, ' ', $decimalTotal == (1.0 as decimal) ? 'yes' : 'no', "\n";
decimal $price = 19.99;
decimal $rate = 0.2;
decimal $goods = $price * 3;
decimal $tax = $goods * $rate;
// Every digit of this is exact. It prints "59.97 + 11.994 = 71.964".
echo $goods, ' + ', $tax, ' = ', $goods + $tax, "\n";
Output
1 no
1.0 yes
59.97 + 11.994 = 71.964

An int and a uint do not mix

<?nvs
// Shows that `+` with an `int` on one side and a `uint` on the other does not compile.
// proof: compile-error
int $change = -1;
uint $stock = 2;
// Convert one side with `as int` or `as uint` first.
echo $stock + $change, "\n";
Output
error[E0407]: `int` and `uint` have no representable common type in arithmetic
--> 04-an-int-and-a-uint-do-not-mix.nvs:9:6
|
9 | echo $stock + $change, "\n";
| ^^^^^^^^^^^^^^^^ mixed-signedness operand
= help: convert one side explicitly with `as int`/`as uint`
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Signs and counting up and down

<?nvs
// Shows the operators written before one number, and `++` and `--`.
int $n = 3;
// `-` changes the sign, `+` keeps it, and `~` flips every bit. This prints `-3 3 -4`.
echo -$n, ' ', +$n, ' ', ~$n, "\n";
// `$n++` gives the old value and then adds one. This prints `3 4`.
echo $n++, ' ', $n, "\n";
// `++$n` adds one and then gives the new value. This prints `5 4`.
echo ++$n, ' ', --$n, "\n";
// `++` also works on a `float`, a `decimal` and an array element. This prints `2.5 11`.
float $f = 1.5;
$f++;
array<int> $counts = [10];
$counts[0]++;
echo $f, ' ', $counts[0], "\n";
// `++` on the largest `int` throws. This prints `Integer addition overflowed`.
int $largest = 9223372036854775807;
try {
$largest++;
} catch (ArithmeticError $overflow) {
echo $overflow->message, "\n";
}
Output
-3 3 -4
3 4
5 4
2.5 11
Integer addition overflowed

Bits and shifts

<?nvs
// Shows the bitwise operators `& | ^ ~` and the shifts `<<` and `>>`.
// This prints `2 7 5 -6`.
echo 6 & 3, ' ', 6 | 3, ' ', 6 ^ 3, ' ', ~5, "\n";
// `<<` shifts left. `>>` on an `int` keeps the sign. This prints `8 -4`.
echo 1 << 3, ' ', -8 >> 1, "\n";
// `>>` on a `uint` fills with zeros. This prints `9223372036854775807 18446744073709551614`.
uint $all = 18446744073709551615;
uint $one = 1;
echo $all >> $one, ' ', ~$one, "\n";
// A shift by a negative count throws. This prints `Bit shift by negative number`.
int $n = 1;
try {
echo $n << -1, "\n";
} catch (ArithmeticError $shift) {
echo $shift->message, "\n";
}
// A shift by 64 or more gives 0, or -1 for a negative `int` shifted right. This prints `0 -1`.
int $negative = -8;
echo $n << 64, ' ', $negative >> 70, "\n";
Output
2 7 5 -6
8 -4
9223372036854775807 18446744073709551614
Bit shift by negative number
0 -1

Details

Each type that is not a number gives a compile error with an arithmetic operator:

  • "3" * 2 and true + 1 are the error E0716. A bool becomes a number with $b ? 1 : 0.
  • A value that can be null, such as a ?float, is the error E0716 too. Test it first with if ($a != null), or give it a default with ??: ($a ?? 0.0) + 1.5.
  • +"3" and -"3" are the error E0705.
  • Two arrays with + are the error E0467.

A mixed value is checked when the program runs. A mixed that is "3" in $m + 1 throws a RuntimeError.

int / int has the type int|float. So float $avg = 7 / 2; compiles, and int $n = 7 / 2; is the error E0401. 6 / 3 is the int 2 when the program runs. Core\Math::quotient(7, 2) is integer division, and it gives 3.

% works on int, uint and decimal. On a float it is the error E0717, and Core\Math::remainder(5.5, 2.0) gives the remainder 1.5. The result has the sign of the number on the left: (-7) % 3 is -1, and 7 % -3 is 1.

int with uint is the error E0407, and so is a shift or a bitwise operator between them. An integer literal next to a uint is a uint, so $u + 3 compiles.

decimal with float is the error E0455, also for a float literal. Write $d + (0.2 as decimal). decimal with int or uint gives a decimal. ** on a decimal is the error E0455 too, and Core\Decimal::power is the power. A decimal division keeps up to 28 digits after the point: 1.0 / 3.0 is 0.3333333333333333333333333333.

** with whole numbers gives a whole number. A negative exponent throws, except with the base 1 or -1: (-1) ** -3 is -1. 2 ** 0.5 is a float.

Each overflow of a whole number throws an ArithmeticError with its own message: Integer addition overflowed, Integer subtraction overflowed, Integer multiplication overflowed, Integer exponentiation overflowed and Integer negation overflowed. 0 - 1 on a uint overflows too. A float that is too large becomes INF and does not throw.

A division by zero throws an ArithmeticError with the message Division by zero. This is also true for a float, such as 1.0 / 0. For a decimal, the error has another message, the same one as a result that is too large. % by zero gives Modulo by zero, and Core\Math::quotient(1, 0) throws as well.

++ and -- work on an int, uint, float or decimal variable, property or array element. On a string they are the error E0474, and on a value such as 3++ the error E0105.

The bitwise operators & | ^ ~ << >> work on int and uint, and give the same type. On a float they are the error E0706. A shift does not check for overflow, so 1 << 63 is -9223372036854775808.

Core\Math::divide divides two float values and returns INF for a division by zero.

Changing a variable

= writes a value into a local variable, a property, a static property or an array element. It is also an expression. Its value is what was just written, so $a = $b = 3 sets both.

Every compound form, such as += or .=, is a short way to write $x = $x op e. The target is worked out once, so $totals[next()] += 1 runs next() once. A compound form cannot change the type of its target, so $n /= 2 on an int does not compile.

??+=, ??-= and ??.= update a value that may not exist yet. $count["paid"] ??+= 1 starts from 0 when the key is missing or the value is null. A string starts from "".

The examples below write and update values, update arrays and objects, and tally a report with ??+=. The last two show every compound operator, and the error for /= on an int.

Writing a value and updating it in place

<?nvs
// Shows `=` writing a value, and the compound forms updating one that is
// already there. `$x += 1` is `$x = $x + 1` written once.
uint $attempts = 0;
string $log = 'start';
// Each of these reads the variable, applies the operator and writes the
// result back.
$attempts += 1;
$attempts += 1;
$log .= ' -> retry';
// This prints: 2 start -> retry
echo $attempts, ' ', $log, "\n";
// The operator keeps the type of the variable it writes into. These all stay
// `int`, and this prints: 7 21 1
int $budget = 10;
$budget -= 3;
echo $budget, ' ';
$budget *= 3;
echo $budget, ' ';
$budget %= 4;
echo $budget, "\n";
// `=` is an expression too, so its value can be used where it stands. Both
// variables end up 3, and the sum is 6.
int $left = 0;
int $right = 0;
$left = $right = 3;
int $sum = $left + $right;
// This prints: 3 3 6
echo $left, ' ', $right, ' ', $sum, "\n";
Output
2 start -> retry
7 21 1
3 3 6

Updating what is inside an array and an object

<?nvs
// Shows the other three things `=` can write into: an array element, a
// property, and a property shared by the whole class. The compound forms
// reach all of them the same way they reach a plain variable.
class Basket
{
public static uint $created = 0;
public function constructor(public decimal $total, public uint $items)
{
Basket::$created += 1;
}
public function add(decimal $price): void
{
// A property is updated in place, exactly like a variable.
$this->total += $price;
$this->items += 1;
}
}
Basket $basket = new Basket(0.00, 0);
$basket->add(19.99);
$basket->add(4.50);
// This prints: 24.49 2
echo $basket->total, ' ', $basket->items, "\n";
// A static property belongs to the class, so every basket made so far has
// counted itself. This prints: 1
echo Basket::$created, "\n";
// An array element takes the same forms. The index is worked out once, even
// with a compound operator.
array<uint> $seen = ['get' => 0, 'post' => 0];
$seen['get'] += 1;
$seen['get'] += 1;
$seen['post'] = 5;
// This prints: 2 5
echo $seen['get'], ' ', $seen['post'], "\n";
Output
24.49 2
1
2 5

Tallying a report as its rows arrive

<?nvs
// Shows what compound assignment is for at work. This report is built by
// updating a few running values once per row. Nothing is collected first and
// added up at the end.
class Order
{
public function constructor(
public string $status,
public decimal $amount,
public uint $items,
)
{}
}
array<Order> $orders = [
new Order('paid', 19.99, 2),
new Order('refunded', 4.50, 1),
new Order('paid', 120.00, 7),
new Order('paid', 8.25, 1),
];
decimal $revenue = 0.00;
array<uint> $byStatus = [];
array<uint> $itemsByStatus = [];
string $large = '';
foreach ($orders as Order $order) {
// `??+=` adds to a count that may not exist yet. The first row for a
// status finds no key, so its count starts at 0 and then becomes 1.
$byStatus[$order->status] ??+= 1;
// This is the same kind of update, written out in full. The first row
// for a status writes the starting value, and `+=` then adds to it.
if (!Core\Arr::hasKey($itemsByStatus, $order->status)) {
$itemsByStatus[$order->status] = 0;
}
$itemsByStatus[$order->status] += $order->items;
// These two values exist from the start, so the plain `+=` and `.=` are
// enough.
if ($order->status == 'paid') {
$revenue += $order->amount;
}
if ($order->items > 5) {
$large .= $order->status . ' ';
}
}
// This prints: 148.24 taken over 10 items
echo $revenue, ' taken over ', $itemsByStatus['paid'], " items\n";
// This prints: paid 3, refunded 1
echo 'paid ', $byStatus['paid'], ', refunded ', $byStatus['refunded'], "\n";
// This prints: large orders: paid
echo 'large orders: ', Core\Str::trim($large), "\n";
Output
148.24 taken over 10 items
paid 3, refunded 1
large orders: paid

Every compound operator

<?nvs
// Shows each compound operator on an `int`, and `/=` on a `float`.
// Each line changes `$n` and prints the new value.
int $n = 10;
$n += 5;
echo $n, ' ';
$n -= 3;
echo $n, ' ';
$n *= 2;
echo $n, ' ';
$n %= 7;
echo $n, ' ';
$n **= 3;
echo $n, ' ';
$n <<= 1;
echo $n, ' ';
$n >>= 2;
echo $n, ' ';
$n &= 7;
echo $n, ' ';
$n |= 8;
echo $n, ' ';
$n ^= 1;
// This line prints: 15 12 24 3 27 54 13 5 13 12
echo $n, "\n";
// `/` can give a fraction, so `/=` works on a `float`. This prints 4.5.
float $f = 9.0;
$f /= 2;
echo $f, "\n";
Output
15 12 24 3 27 54 13 5 13 12
4.5

Dividing an int in place

<?nvs
// Shows that `/=` does not compile on an `int`. `/` can give a `float`, and `$n` is always an `int`.
// proof: compile-error
int $n = 4;
$n /= 2;
Output
error[E0401]: expected `int`, found `int|float`
--> 05-dividing-an-int-in-place.nvs:6:1
|
6 | $n /= 2;
| ^^^^^^^ this is `int|float`
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

The compound forms are +=, -=, *=, /=, %=, **=, .=, <<=, >>=, &=, |= and ^=. There is no <=>= and no |>=.

A compound form needs a value that fits the type of the target. Each of these is the error E0401:

  • $n /= 2 on an int, because / gives int|float
  • $n += 1.5 on an int
  • $n .= "x" on an int

$f += 1 on a float works, because the int is widened. A bitwise form on a float, such as $f |= 1, is the error E0706. On an ?int, $a += 1 is the error E0716, even when the value is not null. Use ??+= or test the value first.

A compound form throws the errors of its operator. On an int or a uint, a result out of range throws an ArithmeticError, and so does $n %= 0. $n **= -1 on an int throws too.

A compound form on an array element reads the element first. $a["k"] += 1 throws a RuntimeError when the key "k" is missing. ??+= starts a missing key at 0.

The left side must be a place to store a value. Writing to a constant or to a call, such as P::X = 2, is the error E0105. Writing a readonly property after the constructor is the error E0782. A write to a variable that was never declared is the error E0301. A parameter is a variable, so a method may write to it.

if ($a = 0) compiles. It writes 0 and tests the value written, so the else block runs.

&, |, ^, ~, << and >> work on the bits of an int or a uint. 6 & 3 is 2, and 1 << 3 is 8. Both sides need the same type.

  • Do use Core\Math::quotient when you need a whole number from a division.
  • Do catch ArithmeticError where a divisor comes from user input.
  • Don’t mix int and uint in one expression. Convert one side with as first.
  • Don’t use /= on an int variable. Use a float variable.