Control Structures in PHP
Control structures allow you to control the flow of execution of your PHP code. They are used to make decisions, repeat actions, and more.
If Statement
The if statement executes code if the condition is true:
<?php
$age = 18;
if ($age >= 18) {
echo "You are an adult.";
}
?>
Else If and Else
You can also use else if and else to create more complex conditions:
<?php
$age = 16;
if ($age >= 18) {
echo "You are an adult.";
} else if ($age >= 13) {
echo "You are a teenager.";
} else {
echo "You are a child.";
}
?>
Activity
Try It Yourself!
Write an if statement that checks if a number is even or odd.
Quiz
Quick Quiz
- What is the purpose of the
else ifstatement? - What happens if none of the conditions in an
ifblock are true?
Answers: The else if is used to test another condition; the else block will execute if none of the previous conditions are true.