Skip to content

Comparison and logic

== checks if two values are equal, and != checks if they are different. Neither operator converts a value to another type. &&, || and ! combine conditions.

Comparison

== tests whether two values are equal, and != tests whether they are different.

Neither operator converts a value, so 1 == "1" does not compile. Numbers of different types do compare, so 1 == 1.0 is true. Two arrays are equal when they have the same keys and values in the same order. Two objects of your own class are equal only when they are the same object.

Dates, times, instants, durations and time zones from Core\Time are compared by their value, so 90m == 1h30m is true. A DateTime is compared by its moment. 10:00 in Europe/Berlin and 09:00 in Europe/London on the same winter day are equal.

<, <=, >, >= and <=> put two values in order. They work on numbers, on bool values and on objects of a class that implements Comparable. Use Core\Str::compare to order two strings.

The examples below compare text, arrays, objects and a missing value, and put two offers in order. Two show compile errors. The last one compares dates and durations.

Checking a number that arrived as text

<?nvs
// Shows how to compare a value that arrived as text with a number you hold.
// `==` converts nothing, so you convert one side yourself and the comparison
// then says what you meant.
// The quantity came from a form field, so it is text.
string $typed = '42';
int $inStock = 42;
// Convert the text to a number and compare two numbers. This prints 1, which
// is how `true` reads as text.
echo (($typed as int) == $inStock) as string, "\n";
// Converting the other way works too, and compares two pieces of text.
echo ($typed == ($inStock as string)) as string, "\n";
// Text is compared character by character and is never read as a number.
// This prints an empty line, which is how `false` reads as text.
echo ($typed == '042') as string, "\n";
// Numbers of different kinds are one family and compare without any
// conversion, so a whole number can equal a decimal one. This prints 1.
float $price = 42.0;
echo ($inStock == $price) as string, "\n";
Output
1
1
1

Comparing arrays objects and a missing value

<?nvs
// Shows `==` on two arrays, on two objects of your own class, and on a value
// that may be missing.
class Customer
{
public function constructor(public string $email)
{}
}
// Two arrays are equal when they have the same keys in the same order with
// equal values. This prints 1 and then an empty line.
array<int> $wanted = [2, 1];
array<int> $picked = [2, 1];
array<int> $reversed = [1, 2];
echo ($wanted == $picked) as string, "\n";
echo ($wanted == $reversed) as string, "\n";
// Two objects of your own class are equal only when they are the same object. Two customers
// built from the same address are two objects, so this prints an empty line.
Customer $signedUp = new Customer('ada@example.com');
Customer $justRead = new Customer('ada@example.com');
echo ($signedUp == $justRead) as string, "\n";
// To check whether they are the same person, compare their properties. This
// prints 1.
echo ($signedUp->email == $justRead->email) as string, "\n";
// A value that may be missing is written `?string`, and you compare it with
// `null` to find out. This prints "no coupon".
?string $coupon = null;
if ($coupon == null) {
echo "no coupon\n";
} else {
// In this branch the coupon is known to be there, so you can use it
// without testing it again.
echo 'coupon of ', Core\Str::length($coupon), " characters\n";
}
Output
1
1
no coupon

Putting two delivery offers in order

<?nvs
// Shows how to order values: numbers compare directly, text uses
// `Core\Str::compare`, and a class states its own order by implementing
// `Comparable`. This is the shape a checkout page uses to pick an offer.
class Offer implements Comparable
{
public function constructor(public string $carrier, public int $cents, public int $days)
{}
// `compareTo` returns a negative number when this offer comes first, and
// a positive one when it comes last. The cheaper offer wins.
public function compareTo(self $other): int
{
if ($this->cents != $other->cents) {
return $this->cents <=> $other->cents;
}
return Core\Str::compare($this->carrier, $other->carrier);
}
}
Offer $standard = new Offer('Speedy', 499, 4);
Offer $express = new Offer('Speedy', 1299, 1);
// `<=>` on two offers returns what `compareTo` returns. This prints -1,
// because 499 comes before 1299.
echo $standard <=> $express, "\n";
// Because `Offer` implements `Comparable`, the ordering operators work on two
// offers directly. This prints "Speedy at 499".
Offer $cheapest = $standard < $express ? $standard : $express;
echo $cheapest->carrier, ' at ', $cheapest->cents, "\n";
// A delivery promise is worth paying for when it is at least two days sooner.
// This prints "worth it".
if ($express->days <= $standard->days - 2) {
echo "worth it\n";
} else {
echo "not worth it\n";
}
Output
-1
Speedy at 499
worth it

A number compared with text

<?nvs
// Shows that `==` between an `int` and a string does not compile. Convert one side with `as` first.
// proof: compile-error
int $quantity = 1;
if ($quantity == '1') {
echo "one item\n";
}
Output
error[E0466]: `int` and `string` are disjoint; no value is both, so this comparison is always false
--> 04-a-number-compared-with-text.nvs:6:5
|
6 | if ($quantity == '1') {
| ^^^^^^^^^^^^^^^^ compared here
= help: convert one side deliberately and then compare — `$s == ($n as string)`
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Two strings with less than

<?nvs
// Shows that `<` between two strings does not compile. `Core\Str::compare` orders two strings.
// proof: compile-error
echo ('apple' < 'banana') ? 'apple first' : 'banana first', "\n";
Output
error[E0715]: `<` has no meaning for `string`
--> 05-two-strings-with-less-than.nvs:5:7
|
5 | echo ('apple' < 'banana') ? 'apple first' : 'banana first', "\n";
| ^^^^^^^^^^^^^^^^^^ ordered here
= help: to compare two strings, use `Core\Str::compare($a, $b)`. The operators `<`, `<=`, `>`, `>=` and `<=>` work only on numbers
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Dates and durations compare by value

<?nvs
// Shows that `==` compares dates and durations by their value, and objects of your own class by identity.
class Order
{
public function constructor(public int $number)
{}
}
// Two `Date` objects for the same day are equal. This prints "same day".
var $shipped = Core\Time\Date::at(2026, 3, 9);
var $delivered = Core\Time\Date::fromIso('2026-03-09');
echo $shipped == $delivered ? 'same day' : 'other day', "\n";
// Two durations with the same length are equal. This prints "true".
Core\Time\Duration $planned = 90m;
Core\Time\Duration $actual = 1h30m;
echo $planned == $actual ? 'true' : 'false', "\n";
// A `DateTime` is compared by its moment. 10:00 in Berlin is 09:00 in London
// on this day, so this prints "same moment".
var $inBerlin = Core\Time\DateTime::at($shipped, Core\Time\TimeOfDay::at(10, 0), 'Europe/Berlin');
var $inLondon = Core\Time\DateTime::at($shipped, Core\Time\TimeOfDay::at(9, 0), 'Europe/London');
echo $inBerlin == $inLondon ? 'same moment' : 'other moment', "\n";
// Two objects of your own class are equal only when they are the same object.
// These two orders have the same number, so this prints "false".
Order $first = new Order(17);
Order $second = new Order(17);
echo $first == $second ? 'true' : 'false', "\n";
// The same object is equal to itself. This prints "true".
Order $again = $first;
echo $first == $again ? 'true' : 'false', "\n";
Output
same day
true
same moment
false
true

Details

== and != are the only two equality operators.

Six Core\Time classes are compared by their value: Date, TimeOfDay, Instant, Duration, Zone and DateTime. Two Date objects for the same day are equal. A DateTime is compared by its moment, so the same moment in two time zones is equal.

Two values whose types can never be equal are the error E0466. Its message tells you to convert one side first. The error covers these pairs:

  • an int and a string, such as 1 == "1"
  • an enum case and an int. Compare $e as int with the number instead.
  • a type that cannot be null and null, such as $n == null for an int
  • a string and bytes
  • objects of two classes that are not related

A class and an interface compile, even when the class does not implement the interface. A child class could implement it.

int and uint compare exactly, with no conversion: -1 == 18446744073709551615 is false, and -1 < 18446744073709551615 is true. decimal ignores trailing zeros: 1.10 == 1.1 is true. float keeps its rounding, so 0.1 + 0.2 == 0.3 is false.

Two strings are equal when they have the same code points (the numbers that make up the text). So "é" written as one code point is not equal to "e" followed by a combining accent.

An array<int> and an array<float> compare element by element, so [1] == [1.0] is true. ["x" => 1, "y" => 2] is not equal to ["y" => 2, "x" => 1], because the keys are in another order. Two anonymous functions are equal only when they are the same function.

A ?T value compared with null tests whether there is a value. In the branch where $u != null is true, $u is a T.

Two mixed values are compared when the program runs. Values of different types are not equal, so a mixed 1 is not equal to a mixed "1". Numbers of different types are equal when the numbers are the same: a mixed 1 is equal to a mixed 1.0.

<, <=, >, >= and <=> give a compile error on any other pair:

  • two strings, two enum cases, two arrays or null are the error E0715. Order an enum by its number with ($a as int) < ($b as int).
  • two objects of a class that does not implement Comparable are the error E0411.
  • objects of two different classes are the error E0411, even when both implement Comparable.

A ?int compiles with <. When the value is null, the comparison throws a RuntimeError, such as "no ordering for a null against a int". Two mixed strings throw a RuntimeError too.

On numbers, <=> returns -1, 0 or 1. On two objects, < calls compareTo and compares its result with 0. <=> returns the result of compareTo unchanged. So when compareTo returns -40, $a <=> $b is -40. false <=> true is -1.

Logic

&& means "both", || means "either" and ! means "not". Each one tests its operands as conditions and returns true or false. The result is always a bool.

Every value counts as true except these: false, null, zero, an empty string, the string "0" and an empty array. A bytes value is false only when it is empty. An object, a callable and an enum case are always true.

&& and || stop when the result is known. In $count != 0 && $total / $count > 10.0, the division runs only when $count is not zero.

Good to know: and, or and xor are not part of the language.

A value that can be null, such as an ?int, is false for null and also for 0. The compiler gives warning W1023 when you test such a value directly. Write != null to check whether there is a value.

The examples below show a check that reads a value only when the value exists, the values of a form field that count as empty, and the checks a request must pass.

A guard that runs the second check only when it is safe

<?nvs
// Shows why `&&` and `||` stop early. The right side runs only when the left
// side has not already given the answer. A check on the left can protect the
// code on the right.
class Report
{
public static function averageIsHigh(int $total, int $count): bool
{
// A division by zero throws an error, so the count is checked first.
// When the count is zero, the division never runs.
return $count != 0 && $total / $count > 10.0;
}
}
// This prints an empty line, which is how `false` reads as text. The
// division was never attempted.
echo Report::averageIsHigh(50, 0) as string, "\n";
// This prints 1, because 50 divided by 4 is more than 10.
echo Report::averageIsHigh(50, 4) as string, "\n";
// `||` is the other way round: it stops as soon as one side is true. The
// second check runs only when the first one failed.
array<string> $chosen = [];
array<string> $suggested = ['novis'];
if ($chosen != [] || $suggested != []) {
echo "something to show\n";
}
Output
1
something to show

Which values count as false when a field arrives

<?nvs
// Shows which values count as false when you test one directly, and the two
// that catch people out: the text "0" is false, while the text "0.0" is
// true.
// A quantity arrived from a form as text.
string $quantity = '0';
// Testing the text directly checks whether it is empty or the one character
// "0". This prints "nothing ordered".
if ($quantity) {
echo "something ordered\n";
} else {
echo "nothing ordered\n";
}
// To check whether the field was filled in, compare it with empty text. This
// prints "the field was filled in".
if ($quantity != '') {
echo "the field was filled in\n";
}
// `as ?int` gives `null` when the text is not a number. Compare the result
// with `null`, because `0` is false too. This prints "the quantity is a number".
if (($quantity as ?int) != null) {
echo "the quantity is a number\n";
}
// An empty array is false, and an array with anything in it is true, even
// when that is a zero. This prints "no tags" and then "has sizes".
array<string> $tags = [];
array<int> $sizes = [0];
if (!$tags) {
echo "no tags\n";
}
if ($sizes) {
echo "has sizes\n";
}
// An object is always true, whatever is inside it. This prints "have a
// basket".
class Basket
{
public function constructor(public int $items)
{}
}
Basket $basket = new Basket(0);
if ($basket) {
echo "have a basket\n";
}
Output
nothing ordered
the field was filled in
the quantity is a number
no tags
has sizes
have a basket

The checks a request runs before it is allowed through

<?nvs
// Shows the shape a request check has at work: several conditions joined
// with `&&`, an alternative joined with `||`, and `!` for the one that has
// to be absent. The result is a `bool`, so it can be stored and passed on.
class Visitor
{
public function constructor(
public string $role,
public bool $emailConfirmed,
public bool $suspended,
public uint $strikes,
)
{}
// Every part has to hold, and the whole thing is one `bool`. `!` reads
// "not suspended".
public function mayPost(): bool
{
return $this->emailConfirmed && !$this->suspended && $this->strikes < 3;
}
// Either role is enough, and the second is checked only when the first
// one does not match.
public function maySeeReports(): bool
{
return $this->role == 'admin' || $this->role == 'auditor';
}
}
Visitor $member = new Visitor('member', true, false, 1);
Visitor $blocked = new Visitor('member', true, true, 0);
Visitor $auditor = new Visitor('auditor', true, false, 0);
// This prints 1, then an empty line for the suspended visitor.
echo $member->mayPost() as string, "\n";
echo $blocked->mayPost() as string, "\n";
// This prints an empty line, then 1.
echo $member->maySeeReports() as string, "\n";
echo $auditor->maySeeReports() as string, "\n";
// The answer is an ordinary `bool`, so it can be stored and combined again.
bool $canDoBoth = $auditor->mayPost() && $auditor->maySeeReports();
echo $canDoBoth as string, "\n";
Output
1
1
1

Details

and, or and xor are the error E0226. Write && for and and || for or. For xor on two bool values, write $a != $b.

&&, || and ! always return a bool. 5 && 3 is true, and !!$x gives the truth value of $x as a bool. A call that returns void is not an operand: Log::write() && $ok is the error E0718.

A few values are easy to get wrong. The string "0.0" and a string with one space are true. NAN (the float that is not a number) is true. -0.0, a decimal 0.00 and a uint 0 are false.

The right side of && and || is narrowed like the branches of an if. The narrowing feature explains the rules. After the whole expression, nothing it tested is kept. So bool $ok = $u != null && $u->active; compiles, but a $u->active on the next line is the error E0459.

Warning W1023 is given when the whole condition of an if, a while, a ? : or a ?: can be null. It is also given for a ?User, which is false only for null. It is not given for an operand of &&, || or !. So if ($n && $ok) with an ?int $n gives no warning, and null and 0 are both false there.

== compares a value from Core\Time by its value. Two Date objects for the same day are equal, and 90m == 1h30m is true. This works for Date, TimeOfDay, Instant, Duration, Zone and DateTime. Objects of your own classes are equal only when they are the same object.

A DateTime is compared by its moment. 10:00 in Europe/Berlin and 09:00 in Europe/London on the same day are equal, even though they print different text. <, <=, > and >= also work on two DateTime values, so you can put events from different time zones in order.

< and > do not work on strings. Core\Str::compare($a, $b) returns -1, 0 or 1.

  • Do test a nullable value with != null && before you use it on the same line.
  • Do use Core\Str::compare to sort strings.
  • Don’t write and, or or xor. Write && for and and || for or. For xor, write != between two bool values.
  • Don’t write ===. == already compares without converting.