Control structures are essential for controlling the flow of your PHP code. In this lesson, we'll cover conditional statements and loops, which allow you to make decisions based on certain conditions and execute code repeatedly.
In PHP, you can use if
, else
, and elseif
statements to perform different actions based on certain conditions.
$age = 18;
if ($age >= 18) {
echo "You are an adult.";
} elseif ($age >= 13) {
echo "You are a teenager.";
} else {
echo "You are a child.";
}
A switch
statement can be used as an alternative to multiple if
and elseif
statements when you need to perform different actions based on the value of a single variable.
$day = "Monday";
switch ($day) {
case "Monday":
echo "Today is Monday.";
break;
case "Tuesday":
echo "Today is Tuesday.";
break;
case "Wednesday":
echo "Today is Wednesday.";
break;
default:
echo "Invalid day.";
}
Loops allow you to execute a block of code repeatedly. PHP supports several types of loops:
for
loop: Runs a block of code a specified number of times.for ($i = 1; $i <= 10; $i++) {
echo "The number is: $i<br>";
}
while
loop: Runs a block of code as long as a specified condition is true.$i = 1;
while ($i <= 10) {
echo "The number is: $i<br>";
$i++;
}
do-while
loop: Runs a block of code once, then repeats the loop as long as a specified condition is true.$i = 1;
do {
echo "The number is: $i<br>";
$i++;
} while ($i <= 10);
foreach
loop: Iterates over an array or an object, running a block of code for each element.$fruits = array("apple", "banana", "cherry");
foreach ($fruits as $fruit) {
echo "The fruit is: $fruit<br>";
}
Practice using control structures in PHP by completing the following exercises:
if
statement.