← Retour au cours: PHP from scratch

Operators and comparisons without surprises

Vidéo bientôt disponible

Operators are the symbols that combine values: they add, compare, join. Almost all are the ones you know from mathematics, but PHP has some details of its own that cause classic bugs, especially when comparing. This lesson teaches you the essential operators and how to avoid the traps of automatic type conversion, something PHP calls type juggling.

Arithmetic and assignment

Addition (+), subtraction (-), multiplication (*), division (/), modulo or remainder (%) and power (**). Normal division returns a float when it is not exact; if you only want the integer part use intdiv. Compound assignment operators such as +=, -=, *= and .= (to join text) shorten expressions like $x = $x + 1. Also ++ and -- add or subtract one. With decimals be careful: 0.1 + 0.2 is not exactly 0.3 in any language that uses floats, and for money it is better to work in cents with integers.

php
<?php

echo 7 + 3, ' ', 7 - 3, ' ', 7 * 3, "\n";   // 10 4 21
echo 7 / 2, ' ', intdiv(7, 2), ' ', 7 % 2, "\n"; // 3.5 3 1
echo 2 ** 10, "\n";                           // 1024

$total = 10;
$total += 5;      // 15
$total *= 2;      // 30
$total++;         // 31
echo $total, "\n";

$message = 'Hello';
$message .= ', world';   // append text
echo $message, "\n";

var_dump(0.1 + 0.2 == 0.3);                    // bool(false)
var_dump(abs((0.1 + 0.2) - 0.3) < 0.00001);    // bool(true)

// Money in cents
$price_cents = 1999;
echo number_format($price_cents / 100, 2), "\n"; // 19.99

Comparison: == versus ===

The == operator compares values converting types if needed; === compares value and type at the same time. In PHP 8 comparing a number with a non-numeric text is done by converting the number to text, which fixes many old oddities, but == can still give results you do not expect, such as '1' == '01' being true. The recommendation is clear: always use === and !== unless you have a concrete reason otherwise.

php
<?php

var_dump(5 == '5');       // bool(true)  loose
var_dump(5 === '5');      // bool(false) strict
var_dump('1' == '01');    // bool(true)
var_dump('1' === '01');   // bool(false)
var_dump(null == false);  // bool(true)
var_dump(null === false); // bool(false)
var_dump(0 == 'abc');     // bool(false) in PHP 8 (was true in PHP 7)

// Spaceship operator: -1, 0 or 1
echo 3 <=> 5, ' ', 5 <=> 5, ' ', 9 <=> 5, "\n"; // -1 0 1

// Different from, greater or equal
var_dump(10 !== '10', 10 >= 10);

Logical and default-value operators

&& (and), || (or) and ! (not) combine conditions. PHP evaluates from left to right and stops as soon as it knows the result (short circuit), so in $user !== null && $user['active'] the second term is not touched if the first is false. The ternary operator condition ? a : b chooses between two values. The null coalescing operator ?? gives a default value if the variable does not exist or is null, without generating warnings: it is the perfect ally for reading optional data. The ??= variant assigns only if it was empty.

php
<?php

$age = 20;
$has_ticket = true;

if ($age >= 18 && $has_ticket) {
    echo "Welcome\n";
}

$label = $age >= 18 ? 'adult' : 'minor';
echo $label, "\n";

$settings = ['theme' => 'dark'];
$theme = $settings['theme'] ?? 'light';       // dark
$language = $settings['lang'] ?? 'en';        // en, no warning
$settings['page_size'] ??= 10;                // assigned only if missing

echo $theme, ' ', $language, ' ', $settings['page_size'], "\n";

// Short ternary: first value if truthy, otherwise the second
$nickname = '';
echo ($nickname ?: 'anonymous'), "\n";   // anonymous

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →