If / Else Conditions
PHPConditions let your PHP code make decisions. If something is true, do one thing — otherwise, do something else.
Basic if statement
PHP
<?php
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
}
// Output: You are an adult.
?>if / else
PHP
<?php
$score = 65;
if ($score >= 70) {
echo "Pass!";
} else {
echo "Fail. Try again.";
}
// Output: Fail. Try again.
?>if / elseif / else
PHP
<?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
?>Ternary Operator
PHP
<?php
$age = 20;
$status = ($age >= 18) ? "adult" : "minor";
echo $status; // adult
?>Switch Statement
PHP
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week!";
break;
case "Friday":
echo "Almost weekend!";
break;
case "Saturday":
case "Sunday":
echo "Weekend!";
break;
default:
echo "Midweek.";
}
?>Null Coalescing Operator (PHP 7+)
PHP
<?php
// Returns left side if not null, otherwise right side
$username = $_GET['user'] ?? 'Guest';
echo $username; // Guest (if no user param in URL)
// Chaining
$value = $a ?? $b ?? $c ?? 'default';
?>💡
Use
=== in conditions! Always use strict comparison to avoid unexpected type-juggling bugs in PHP.Test your knowledge!
Take the PHP Basics quiz.