Conditional statements are used to perform different actions for different decisions. They allow your script to make choices, which is the core of dynamic programming.
1. The if Statement
The if statement executes a block of code only if a specified condition is TRUE.
| Syntax | Description |
if (condition) | If the condition evaluates to TRUE, the code inside the curly braces ({}) is executed. |
Example:
PHP
<?php
$t = date("H"); // Gets the current hour (0 to 23)
if ($t < "20") {
echo "Have a good day!";
}
?>
2. The if...else Statement
The if...else statement executes one block of code if the condition is TRUE, and a different block of code if the condition is FALSE.
| Syntax | Description |
if (condition) | Execute this code if the condition is TRUE. |
else | Execute this code if the condition is FALSE. |
Example:
PHP
<?php
$age = 17;
if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are too young to vote.";
}
?>
3. The if...elseif...else Statement
This statement specifies a new condition to test if the first condition is FALSE. You can use any number of elseif blocks.
| Syntax | Description |
if (condition1) | Execute if condition1 is TRUE. |
elseif (condition2) | Execute if condition1 is FALSE AND condition2 is TRUE. |
else | Execute if ALL conditions (1 and 2) are FALSE. |
Example:
PHP
<?php
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B"; // This code will execute
} else {
echo "Grade: C or lower";
}
?>
4. The switch Statement
The switch statement is used to perform different actions based on different conditions, but for a single variable being compared against multiple possible values. It’s often cleaner than a long if...elseif...else chain.
| Syntax | Description |
switch ($variable) | The variable being checked. |
case value: | Execute code if $variable matches this value. |
break; | Crucial: Stops the execution from running into the next case. |
default: | Executes if no other case matches. |
Example:
PHP
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "Almost the weekend!";
break;
default:
echo "Just a regular day.";
}
?>
