Beginner Fundamentals

PHP Conditionals

Conditionals let your program make decisions and run different code depending on whether something is true or false.

The if statement

Code inside the braces runs only when the condition is true.

<?php
$age = 20;
if ($age >= 18) {
    echo "You are an adult";
}

if, elseif, else

Chain conditions to handle multiple cases.

<?php
$score = 75;

if ($score >= 90) {
    echo "Grade A";
} elseif ($score >= 70) {
    echo "Grade B";
} else {
    echo "Grade C";
}

The ternary operator

A short way to write a simple if/else that returns a value.

<?php
$age = 16;
$status = ($age >= 18) ? "adult" : "minor";
echo $status; // minor

Null coalescing

Use ?? to provide a default when a value is null or not set.

<?php
$name = $username ?? "Guest";
echo $name; // Guest if $username is undefined