start learning
Image 1

Conditional statements

Conditional statements in PHP allow you to control the flow of your program based on specified conditions. These statements help you make decisions and execute different blocks of code depending on whether a condition is true or false.

PHP provides several conditional statements :


if Statement

The if statement executes a block of code if a specified condition evaluates to true. Optionally, you can include elseif and else clauses for additional conditions.


$age = 25;
if ($age < 18) {
    echo "You are a minor.";
} elseif ($age >= 18 && $age < 65) {
    echo "You are an adult.";
} else {
    echo "You are a senior citizen.";
}
 

switch Statement

The switch statement allows you to select one of many blocks of code to be executed, based on the value of an expression.


$day = "Monday";
switch ($day) {
    case "Monday":
        echo "It's the beginning of the week.";
        break;
    case "Friday":
        echo "It's almost the weekend.";
        break;
    default:
        echo "It's an ordinary day.";
}
 

Ternary Operator (?:)

The ternary operator is a shorthand way of writing simple if...else statements. It returns one of two values depending on whether a condition is true or false.


$age = 20;
$message = ($age < 18) ? "You are a minor." : "You are an adult.";
echo $message;
 

Null Coalescing Operator (??)

The null coalescing operator allows you to check if a variable is set and not null. It returns the left operand if it's not null; otherwise, it returns the right operand.


$username = $_GET['user'] ?? 'Guest';
echo "Hello, $username!";
 

These conditional statements are fundamental to making decisions in your PHP code and executing different logic paths based on conditions. They help you create dynamic and responsive applications by controlling the flow of your code.