PHP & MySQL

PHP if-else, Comparison & Logical Operators

Guide to PHP conditionals - if/else, ternary, null coalescing, match expressions, comparison operators, and type juggling.

if / else / elseif

<?php
$score = 85;

if ($score >= 90) {
    echo 'Grade: A';
} elseif ($score >= 80) {
    echo 'Grade: B';
} elseif ($score >= 70) {
    echo 'Grade: C';
} else {
    echo 'Grade: F';
}
// Output: Grade: B

Comparison Operators

OperatorNameExampleResult
==Equal (loose)1 == "1"true
===Identical (strict)1 === "1"false
!=Not equal (loose)1 != "2"true
!==Not identical1 !== "1"true
<Less than5 < 10true
>Greater than10 > 5true
<=>Spaceship1 <=> 2-1

== vs === (Critical Difference)

<?php
// Loose comparison (==) performs type juggling
var_dump(0 == "foo");    // true (!) -"foo" converts to 0
var_dump("" == false);   // true
var_dump(null == false);  // true
var_dump("0" == false);  // true

// Strict comparison (===) checks type AND value
var_dump(0 === "foo");   // false ✓
var_dump("" === false);  // false ✓
var_dump(null === false); // false ✓

// BEST PRACTICE: Always use === unless you have
// a specific reason to use ==

Logical Operators

OperatorNameDescription
&&ANDBoth must be true
||ORAt least one true
!NOTInverts boolean
andAND (low precedence)Same as && but lower priority
orOR (low precedence)Same as || but lower priority
xorXOROne true, but not both
<?php
$age = 25;
$hasLicense = true;

if ($age >= 18 && $hasLicense) {
    echo 'Can drive';
}

if ($age < 13 || $age > 65) {
    echo 'Discount applies';
}

if (!$hasLicense) {
    echo 'Cannot drive';
}

Ternary & Null Coalescing

<?php
// Ternary: condition ? if_true : if_false
$status = ($score >= 60) ? 'pass' : 'fail';

// Short ternary (Elvis operator)
$name = $username ?: 'Guest';  // uses $username if truthy

// Null coalescing (??)
$color = $_GET['color'] ?? 'blue';  // 'blue' if not set or null

// Null coalescing assignment (??=)  PHP 7.4+
$config['timeout'] ??= 30;  // sets to 30 only if null/unset

match Expression (PHP 8.0+)

<?php
$status = match($code) {
    200 => 'OK',
    301 => 'Moved Permanently',
    404 => 'Not Found',
    500 => 'Server Error',
    default => 'Unknown',
};

// match uses strict comparison (===)
// match throws UnhandledMatchError if no match + no default

Last updated: 2026 • Browse all courses