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.
Else statement
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.";
}
- $num is a variable representing a number.
- The condition in the if statement checks if $num is even by using the modulo operator %. If the remainder when dividing by 2 is 0, it's even.
- If the condition is true, it displays "$num is even."
- If the condition is false, it executes the code inside the else block, which displays "$num is odd."
User Authentication
$isAuthenticated = true;
if ($isAuthenticated) {
echo "Welcome to our website!";
} else {
echo "Please log in to access the content.";
}
- $isAuthenticated is a boolean variable indicating whether a user is authenticated (true) or not (false).
- The condition in the if statement checks if $isAuthenticated is true.
- If the condition is true, it displays "Welcome to our website!"
- If the condition is false (user is not authenticated), it executes the code inside the else block, which displays "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.";
}
- $input is a variable representing some user input (in this case, an empty string).
- The condition in the if statement checks if $input is empty using the empty() function.
- If the condition is true (input is empty), it displays "Input is empty."
- If the condition is false (input is not empty), it executes the code inside the else block, which displays "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.
×