Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Conditions

Conditions let a program choose which code to run. Without them a program would always do the same thing, whatever the data.

if and else

The code in braces after if runs only when the condition is true. The else block runs otherwise:

<?php
 
$age = 20;
 
if ($age >= 18) {
    echo 'Access granted';
} else {
    echo 'Access denied';
}

The else block is optional: if you do not need it, leave it out.

Several branches

When there are more than two options, add elseif between if and else. Conditions are checked from top to bottom, and the first matching block runs:

<?php
 
$score = 75;
 
if ($score >= 90) {
    echo 'Excellent';
} elseif ($score >= 70) {
    echo 'Good';
} else {
    echo 'Needs work';
}

Order matters: if the >= 70 check came first, a score of 95 would also get "Good".

The ternary operator

A short form of if-else for choosing one of two values. The condition comes first, the value for true follows ?, the value for false follows ::

<?php
 
$age = 15;
 
echo $age >= 18 ? 'adult' : 'child'; // child

The ternary operator suits simple cases. Leave complex logic to a regular if — it is easier to read.

Default values

The ?? operator returns the left value if it exists and is not null, and the right value otherwise:

<?php
 
$input = null;
$name = $input ?? 'Guest';
 
echo $name; // Guest

It is the most convenient way to supply a default.

match

The match expression compares a value against several options and returns the result of the matching one:

<?php
 
$status = 404;
 
$text = match ($status) {
    200 => 'OK',
    404 => 'Not found',
    default => 'Unknown status',
};
 
echo $text; // Not found

match compares strictly, like ===. If nothing matches and there is no default arm, PHP throws an error.

A common mistake

Braces after if may be omitted when the body is a single statement. Do not do that: add a second line and it will always run, outside the condition. Always use braces.

Thanks for reading!

Donate to the site — we work hard for you.