Thuta Learning
PHP
BasicProgrammingBeginner

Operators

PHPLesson 1030 min

What you'll walk away with

  • Tell == from === and avoid loose comparisons whose result you cannot predict
  • Explain the -1, 0 and 1 results of <=> and use it in a sorting callback
  • Explain the difference between ?? and ?: and pick the right one
  • Predict short-circuiting of && and ||, the and/or precedence trap, and the PHP 8 precedence of the dot

Explain it simply

Explain it simply

Operators are the symbols that combine values into a new value. + adds, >= compares and gives true or false, and && gives true only when both conditions are true. Stock levels, login checks and "is this form field filled in" tests are all built from operators.

That sounds like the easiest topic, but some PHP operators convert types behind your back. Above all, not knowing how == compares can even open a security hole. This lesson makes those parts clear.

Problem → Why → Solution

The problem: two different tokens count as equal

A password-reset link compares the stored token with the one the user sends using ==. The two tokens below are clearly different strings, yet the check passes and "Access granted" appears. An attacker could get in without knowing the real token.

token-check.php
<?php
$storedToken = "0e830400451993494058024219903391";
$givenToken  = "0e462097431906509019562988736854";

if ($storedToken == $givenToken) {
    echo "Access granted" . PHP_EOL;     // runs, although the strings differ
}

Why does == say they are equal?

Both strings start with 0e followed by digits only, so PHP treats them as numeric strings: 0e means 0 times a power of ten, so each one has the value 0. == compares two numeric strings as numbers, so it becomes 0 == 0. === compares the type and every character and returns false; for secret values use hash_equals().

Core concept: operator families and comparison rules

Operators combine values into new values. PHP groups them into families: arithmetic (+ - * / % **), assignment (= += -= .= ??=), comparison (== === != !== < > <= >= <=>), logical (&& || ! and or xor), the string operator (.) and the null-related ones, ?? and ?:. An expression such as $quantity <= $stock produces a bool, and every if, while and ternary simply reads such a bool.

Comparison is where PHP needs the most care. == is loose: if the types differ, PHP converts them before comparing, so '10' == '1e1' is true because both strings are numeric and equal as numbers, and null == false is true. === is strict: type and value must both match, so '10' === '1e1' is false. PHP 8 fixed the notorious 0 == 'abc': a number compared with a non-numeric string is now compared as strings, so it is false (in PHP 7 it was true). Even so, make === and !== your default and use == only when you really want conversion.

<=> is the spaceship operator. It returns -1, 0 or 1 and is made for sorting callbacks such as $a <=> $b in usort(). ?? returns its left side when that is set and not null, otherwise the right side, so $_GET['page'] ?? 1 never warns. ?: (the short ternary) returns the left side when it is truthy, so 0 ?: 'fallback' gives 'fallback' while 0 ?? 'fallback' gives 0. Use ?? for "is it missing?" and ?: for "is it empty?".

Operators have precedence, and && and || short-circuit: in false && f() the function f is never called. The lowercase and and or bind looser than =, so $ok = true and false; stores true in $ok. Since PHP 8, + and - bind tighter than the dot, so 'Total: ' . 5 + 3 prints 'Total: 8' instead of failing; when in doubt, add parentheses. ** is right-associative and binds tighter than unary minus: -2 ** 2 is -4.

Mental model: an operator makes a new value
  1. Operands meet an operator
  2. Loose == converts types, === does not
  3. A value or a bool comes out
  4. if, ?? and ?: then act on it

When the result is unclear, add parentheses and choose ===.

General pattern

php
<?php
$sum = $a + $b;                     // arithmetic: + - * / % **
$same = $a === $b;                  // strict comparison: type and value
$order = $a <=> $b;                 // -1, 0 or 1
$ok = $isReady && !$isBlocked;      // logical: && || !
$value = $input ?? $default;        // default when missing or null
$label = $count > 0 ? "some" : "none";   // ternary
$total += $extra;                   // compound assignment
$text .= "more";                    // append to a string

Put your own expressions in place of $a and $b. Comparison and logical operators produce a bool, and compound assignments such as += calculate and store the result in one step.

Example: a stock check, a coupon and a stock level

This script uses arithmetic, comparison, logical operators, ??, the ternary and <=> together in one small ordering scenario. Watch which operator serves which purpose in each part.

stock-check.php
<?php
$stock = 12;
$orderQty = 3;
$isLoggedIn = true;
$coupon = null;

echo "Remaining stock: " . ($stock - $orderQty) . PHP_EOL;

if ($isLoggedIn && $orderQty <= $stock) {
    echo "Order can be placed." . PHP_EOL;
}

echo "Coupon: " . ($coupon ?? "none") . PHP_EOL;
echo "Stock level: " . ($stock > 10 ? "plenty" : "low") . PHP_EOL;
echo "Compare with 10: " . ($stock <=> 10) . PHP_EOL;

Code breakdown

  1. Line 5$coupon = null;

    null means "no value yet". Here it stands for a customer who has not entered a coupon.

  2. Line 7echo "Remaining stock: " . ($stock - $orderQty) . PHP_EOL;

    The parentheses make the order obvious. In PHP 8 the subtraction would run before the dot anyway, but readers should not have to remember precedence rules. The result is 9.

  3. Line 9if ($isLoggedIn && $orderQty <= $stock) {

    <= produces a bool and && is true only when both sides are. If the left side is false, the right side is not even evaluated (short-circuit).

  4. Line 13echo "Coupon: " . ($coupon ?? "none") . PHP_EOL;

    $coupon is null, so ?? picks "none" from its right side. It would not warn even if the variable did not exist.

  5. Line 14echo "Stock level: " . ($stock > 10 ? "plenty" : "low") . PHP_EOL;

    A ternary reads condition ? if-true : if-false. 12 > 10, so plenty is printed. Keep the parentheses; without them the line is hard to read.

  6. Line 15echo "Compare with 10: " . ($stock <=> 10) . PHP_EOL;

    12 is greater than 10, so <=> returns 1. It would return -1 for smaller and 0 for equal.

You should see
Remaining stock: 9
Order can be placed.
Coupon: none
Stock level: plenty
Compare with 10: 1

Loose and strict comparison, side by side

The table shows what PHP 8 really returns. Notice which rows surprise you; that is why === should be your default.

ExpressionPHP 8 resultWhy
0 == 'a'falsea number vs a non-numeric string is compared as strings
'1' == '01'truetwo numeric strings compare as numbers
'10' == '1e1'true10 and 1e1 are the same number
null == falsetrueboth convert to false
'0' == falsetruethe string '0' is falsy
[] == falsetruean empty array is falsy
'10' === '1e1'falsestrict: every character must match
comparisons.php
<?php
var_dump(0 == "a");         // false in PHP 8
var_dump("1" == "01");      // true
var_dump("10" == "1e1");    // true
var_dump(null == false);    // true
var_dump("10" === "1e1");   // false
var_dump(1 <=> 2, "b" <=> "a", 5 <=> 5);   // -1, 1, 0

?? versus ?: and the ternary

?? tests only for null (or missing), while ?: tests for every falsy value: 0, an empty string, "0" and an empty array. So when 0 is a legitimate value, use ??. ??= assigns only when the target is null, which makes it a neat way to set defaults.

null-handling.php
<?php
$config = ["retries" => 0, "label" => "", "timeout" => null];

var_dump($config["retries"] ?? 3);     // int(0): the key exists and is not null
var_dump($config["retries"] ?: 3);     // int(3): 0 is falsy
var_dump($config["label"] ?? "none");  // string(0) ""
var_dump($config["label"] ?: "none");  // string(4) "none"
var_dump($config["timeout"] ?? 30);    // int(30): null counts as missing
var_dump($config["missing"] ?? 30);    // int(30): no warning for a missing key

$page = null;
$page ??= 1;      // assigned, because $page was null
$page ??= 99;     // ignored, because $page already has a value
echo $page . PHP_EOL;

$age = 20;
echo ($age >= 18 ? "adult" : "minor") . PHP_EOL;

Precedence and short-circuiting

&& and || work left to right and stop as soon as the answer is known. In practice that makes guards such as $user !== null && $user->isAdmin() safe. The second point is the trap of mixing = with and/or; sticking to && and || avoids it entirely.

precedence.php
<?php
function check(string $name): bool
{
    echo "check($name) ";
    return true;
}

var_dump(false && check("a"));   // check() never runs
var_dump(true || check("b"));    // check() never runs
var_dump(true && check("c"));    // check() runs, then the result is printed

$ok = true and false;            // = binds tighter than "and"
var_dump($ok);                   // bool(true)
$ok = (true and false);
var_dump($ok);                   // bool(false)

echo (2 + 3 * 4) . PHP_EOL;      // 14: multiplication first
echo -2 ** 2 . " " . 2 ** 3 ** 2 . PHP_EOL;   // -4 512
echo "Total: " . 5 + 3 . PHP_EOL;             // Total: 8 in PHP 8

In real projects

Where this shows up in real projects

In login, permission and checkout code, operators make the decisions: checks such as $isLoggedIn && $user['role'] === 'admin', form defaults like $_POST['qty'] ?? 1, price formulas like $price * $qty + $shipping, and sorting with usort($rows, fn($a, $b) => $a['date'] <=> $b['date']).

For security, never compare tokens, API keys or password hashes with ==; use hash_equals() and password_verify(). When you compare a user-supplied value such as an ID, remember that a query string is always a string: compare $_GET['id'] === '5', or convert with filter_var() first and then use ===. in_array() and switch also compare loosely, so they share these rules, which makes this lesson the foundation for them as well.

Common mistakes

Common mistakes

1. Using = instead of == inside a condition

if ($role = 'admin') does not compare anything; it assigns 'admin' to $role, and the truthy result always enters the block. PHP 8 gives no warning, and $role silently changes from guest to admin. Use === every time.

2. Comparing secrets with ==

Two tokens shaped like '0e83...' are reported equal by ==. hash_equals($known, $given) compares the two strings exactly and also resists timing attacks.

3. Mixing up ?? and ?:

With $qty = $_POST['qty'] ?? 1; an empty string from the form stays '' and never becomes 1. Use ?: when empty values should also get the default. In the other direction, ?: on a field where 0 is allowed overwrites a valid 0 with the default.

4. Mixing = with and / or

$ok = $a and $b; is read as ($ok = $a) and $b, so the value of $b never reaches $ok. Stick to && and ||, and add parentheses if you must use and or or.

Best practices

Best practices

  • Make === and !== your default, and use == only when you need conversion, with a comment saying why.
  • Add parentheses to complicated expressions so the order is obvious, and use only && and ||.
  • Use ?? for default values and compare secret values with hash_equals().

Mini challenge

Mini challenge: a checkout gate

Write a checkout() function that checks a cart array, the stock and the login state and returns a message. Use ?? for defaults, || and !, and show "sold out" when nothing is left.

  • Use ?? so a missing $cart["qty"] means 1 and a missing $cart["coupon"] means "none"
  • Return "Please log in first." when the customer is not logged in
  • Return "Quantity not available." when qty is below 1 or above the stock
  • Otherwise return "Order placed: N item(s), coupon X, left: Y", showing "sold out" with ?: when nothing is left
checkout.php
<?php
function checkout(array $cart, int $stock, bool $loggedIn): string
{
    // TODO: read qty and coupon with ??
    // TODO: return early when not logged in
    // TODO: return early when qty is below 1 or above $stock
    // TODO: build the success message, using ?: for the "sold out" label
}

// TODO: call checkout() for four carts and echo each result

Expected: Expected output: Order placed: 3 item(s), coupon SAVE10, left: 9 Order placed: 12 item(s), coupon none, left: sold out Please log in first. Quantity not available.

Show hint

$left ?: 'sold out' gives 'sold out' when $left is 0 and $left itself otherwise. ?? would not catch the 0 here.

Show solution
checkout.php
<?php
function checkout(array $cart, int $stock, bool $loggedIn): string
{
    $qty = $cart["qty"] ?? 1;
    $coupon = $cart["coupon"] ?? "none";

    if (!$loggedIn) {
        return "Please log in first.";
    }
    if ($qty < 1 || $qty > $stock) {
        return "Quantity not available.";
    }

    $left = $stock - $qty;
    return "Order placed: $qty item(s), coupon $coupon, left: " . ($left ?: "sold out");
}

echo checkout(["qty" => 3, "coupon" => "SAVE10"], 12, true) . PHP_EOL;
echo checkout(["qty" => 12], 12, true) . PHP_EOL;
echo checkout([], 12, false) . PHP_EOL;
echo checkout(["qty" => 20], 12, true) . PHP_EOL;

Quick quiz 1 / 3

In PHP 8, what does var_dump(0 == "a"); output?

Quick quiz 2 / 3

$qty = 0; echo $qty ?: 5; echo $qty ?? 5; prints what?

Quick quiz 3 / 3

$ok = true and false; var_dump($ok); outputs what?

What to remember

  • == converts types, so two '0e..' tokens can be 'equal'; make === the default and use hash_equals() for secrets.
  • In PHP 8, 0 == 'a' is false, and <=> returns -1, 0 or 1.
  • ?? tests only null or missing while ?: tests every falsy value, so use ?? when 0 is allowed.
  • && and || short-circuit, and/or bind looser than =, and in PHP 8 + and - bind tighter than the dot.

PHP Language Reference — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Operators | Thuta Learning