In PHP, an "if" statement is a conditional statement used to execute a block of code if a specified condition evaluates to true.
If statement
Basic Syntax of an "if" Statement
The basic syntax of an "if" statement in PHP is as follows:
if (condition) {
// Code to execute if the condition is true
}
Simple "if" Statement
$age = 25;
if ($age >= 18) {
echo "You are an adult.";
}
- $age is a variable representing a person's age.
- The condition in the if statement checks if $age is greater than or equal to 18.
- If the condition is true, it executes the code inside the curly braces {}, which in this case, is displaying the message "You are an adult."
"if" and "else" Statement
$score = 65;
if ($score >= 70) {
echo "You passed!";
} else {
echo "You failed.";
}
- $score represents a test score.
- The condition in the if statement checks if $score is greater than or equal to 70.
- If the condition is true, it displays "You passed!"
- If the condition is false, it executes the code inside the else block, which displays "You failed."
"if" Statement with Multiple Conditions
$temperature = 28;
if ($temperature < 32) {
echo "It's freezing!";
}
- $temperature represents the temperature in degrees Fahrenheit.
- The condition in the if statement checks if $temperature is less than 32 (the freezing point of water).
- If the condition is true, it displays "It's freezing!" indicating that it's below freezing.
In each of these examples, the "if" statement evaluates the condition, and if the condition is met (true), the code inside the "if" block is executed. If the condition is not met (false), the code inside the "if" block is skipped (in the absence of an "else" block).
×