CodeMIRAI
0 XP

Operators

2 min read 7 runnable examples Quiz included

Arithmetic

PHP
<?php
$a = 17;
$b = 5;
var_dump($a + $b);       // int(22)
var_dump($a / $b);       // float(3.4): / always divides fully
var_dump(intdiv($a, $b)); // int(3): whole-number division
var_dump($a % $b);       // int(2): the remainder
var_dump(2 ** 10);       // int(1024): powers

Unlike many languages, PHP's / gives a decimal when the division isn't exact, even between two integers. Use intdiv for whole-number division.

Assignment shortcuts

PHP
<?php
$score = 10;
$score += 5;      // 15
$score *= 2;      // 30
$score -= 4;      // 26
$score++;         // 27
echo $score, "\n";

$text = "Hello";
$text .= ", world";   // append a string
echo $text, "\n";

Loose and strict comparison

PHP
<?php
var_dump(5 == "5");       // true: the string is converted first
var_dump(5 === "5");      // false: different types
var_dump(0 == "");        // false in PHP 8
var_dump(null == false);  // true
var_dump(null === false); // false
var_dump("abc" == 0);     // false in PHP 8 (it was true in PHP 7)
  • == converts values to a common type before comparing, which leads to surprises.
  • === is true only when the value and the type match.

Prefer === and !== unless you specifically want conversion. PHP 8 made == saner, so very old tutorials may show different results.

The spaceship operator

PHP
<?php
var_dump(1 <=> 2);    // int(-1): less
var_dump(2 <=> 2);    // int(0): equal
var_dump(3 <=> 2);    // int(1): greater

$prices = [40, 10, 30];
usort($prices, fn($x, $y) => $x <=> $y);
echo implode(", ", $prices), "\n";

<=> returns -1, 0 or 1, exactly what sorting functions expect from a comparison.

Logical operators

PHP
<?php
$age = 19;
$hasTicket = true;
var_dump($age >= 18 && $hasTicket);    // and
var_dump($age < 13 || $age > 65);      // or
var_dump(!$hasTicket);                 // not

PHP also has the words and, or and xor, but they have lower precedence than =: $ok = true and false; sets $ok to true. Stick to && and ||.

Null coalescing: ?? and ??=

PHP
<?php
$settings = ["theme" => "dark"];

$theme = $settings["theme"] ?? "light";
$lang = $settings["lang"] ?? "en";        // missing key: no warning, use the default
echo "$theme $lang\n";

$settings["lang"] ??= "hi";               // set only if missing (or null)
$settings["theme"] ??= "light";           // already set, so unchanged
print_r($settings);

$a ?? $b gives $a if it exists and isn't null, and $b otherwise, without the "undefined" warning you'd get from reading a missing key. It's everywhere in real PHP code, especially for reading form input.

The ternary operator

PHP
<?php
$items = 1;
echo $items . " " . ($items === 1 ? "item" : "items") . "\n";

$name = "";
echo ($name ?: "Guest") . "\n";      // ?: uses the right side when the left is falsy
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.