If Else in PHP

Branching with if and else in PHP is straightforward.

<?php

// Here's a basic example.
if (7 % 2 == 0) {
    echo "7 is even\n";
} else {
    echo "7 is odd\n";
}

// You can have an `if` statement without an else.
if (8 % 4 == 0) {
    echo "8 is divisible by 4\n";
}

// Logical operators like && and || are often useful in conditions.
if (8 % 2 == 0 || 7 % 2 == 0) {
    echo "either 8 or 7 are even\n";
}

// A statement can precede conditionals; any variables
// declared in this statement are available in the current
// and all subsequent branches.
$num = 9;
if ($num < 0) {
    echo "$num is negative\n";
} elseif ($num < 10) {
    echo "$num has 1 digit\n";
} else {
    echo "$num has multiple digits\n";
}

To run the program, save it as if_else.php and use the PHP CLI:

$ php if_else.php
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that you don’t need parentheses around conditions in PHP for if statements, but they are commonly used for clarity. The curly braces {} are required if you have more than one statement in a block.

PHP does have a ternary operator, which provides a shorthand way of writing simple if-else statements:

$result = (condition) ? value_if_true : value_if_false;

This can be useful for simple conditions, but for more complex logic, a full if statement is often more readable.