start learning
Image 1

Else statement

In PHP, an "else" statement is used in conjunction with an "if" statement to execute a different block of code when the specified condition in the "if" statement evaluates to false.


Basic Syntax of an "if" and "else" Statement

The basic syntax of an "if" and "else" statement in PHP is as follows:


if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}
 

Checking if a Number is Even or Odd


$num = 7;

if ($num % 2 == 0) {
    echo "$num is even.";
} else {
    echo "$num is odd.";
}
 


User Authentication


$isAuthenticated = true;

if ($isAuthenticated) {
    echo "Welcome to our website!";
} else {
    echo "Please log in to access the content.";
}
 


Checking for Empty Input


$input = "";

if (empty($input)) {
    echo "Input is empty.";
} else {
    echo "Input is not empty.";
}
 


In each of these examples, the "if" statement checks a condition, and if the condition is true, the code inside the "if" block is executed. If the condition is false, the code inside the "else" block is executed. The "else" statement allows you to provide an alternative action to be taken when the condition is not met.