Originally published on zero2php.dev — part of the Zero to PHP course. View this lesson on the original site.

Logical operators

Combine tests with && (and), || (or), and ! (not).

Example

<?php

declare(strict_types=1);

$age = 20;
$hasTicket = true;

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

Shorthand forms

Ternary ? :

condition ? value_if_true : value_if_false evaluates the condition, then picks one of two expressions. Good for short branches or assignments:

$label = $age >= 18 ? 'adult' : 'minor';
echo $age >= 18 ? 'adult' : 'minor';

Keep each side readable—if the expressions get long, use a normal if instead.

Null coalescing ??

$a ?? $b means: use $a if it exists and is not null; otherwise use $b. Same idea as isset($a) ? $a : $b for variables and array keys, without a notice when $a is missing.

$name = $maybe ?? 'guest';
$port = $config['port'] ?? 8080;

?? is not the same as the ternary with truthiness: $x ?: $y picks $y when $x is “falsy” (empty string, 0, false, etc.). ?? only cares about isset / null.

Manual: Comparison operators — null coalescing

Prefer clarity over clever one-liners while you are learning.

Exercise

Exercise 1 — ternary: Set $age = 20. Use the ternary operator to echo adult if $age >= 18, otherwise minor.

Exercise 2 — null coalescing (??): Set $title = null. echo an expression using ?? so the output is untitled when $title is null (expected stdout: untitled exactly).

From Zero to PHP — Control flow, functions, arrays, and the web