PHP Conditional Statements
Learn how to use conditional statements to control the flow of your PHP code.
What Are Conditional Statements?
Conditional statements allow you to execute different pieces of code based on certain conditions. They help in making decisions in your script.
Types of Conditional Statements
- If Statement
- If...Else Statement
- If...Elseif...Else Statement
- Switch Statement
1. If Statement
The simplest form of a conditional statement. It executes a block of code if the condition is true.
<?php
$age = 18;
if ($age >= 18) {
echo "You are an adult.";
}
?>
2. If...Else Statement
This statement allows you to execute one block of code if the condition is true and another block if it is false.
<?php
$age = 16;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are not an adult.";
}
?>
3. If...Elseif...Else Statement
This statement is used when you have multiple conditions to check.
<?php
$age = 20;
if ($age < 13) {
echo "You are a child.";
} elseif ($age < 20) {
echo "You are a teenager.";
} else {
echo "You are an adult.";
}
?>
4. Switch Statement
The switch statement is used to perform different actions based on different conditions. It is often used as a cleaner alternative to multiple if statements.
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Today is Monday.";
break;
case "Tuesday":
echo "Today is Tuesday.";
break;
default:
echo "Today is not Monday or Tuesday.";
}
?>
Comparison Operators
Conditional statements often use comparison operators to evaluate conditions:
- Equal:
==
- Identical:
===
- Not Equal:
!=
or<>
- Greater Than:
>
- Less Than:
<
- Greater Than or Equal To:
>=
- Less Than or Equal To:
<=
Conclusion
Conditional statements are essential for controlling the flow of your PHP scripts. Understanding how to use them will allow you to make decisions based on dynamic conditions in your code.