Control statements and loops are important constructs in PHP to control the flow of program execution. Control statements allow us to perform different actions based on specified conditions, while loops allow us to repeat a block of code multiple times.
Here are some commonly used control statements and loops in PHP:
If statement
Used to execute a block of code if a condition is true.
Example:
if($age < 18) {
echo "You are not old enough.";
} else {
echo "You are old enough.";
}
Switch statement
Allows you to perform different actions based on the value of an expression.
Example:
switch($dayOfWeek) {
case 1:
echo "Today is Monday.";
break;
case 2:
echo "Today is Tuesday.";
break;
// Other cases...
default:
echo "Today is an unknown day.";
}
For loop
Used to iterate over a block of code for a specified number of times.
Example:
for($i = 0; $i < 5; $i++) {
echo "Giá trị của i là: ". $i;
echo "<br>";
}
While loop
Repeats a block of code as long as a condition is true.
Example:
$i = 0;
while($i < 5) {
echo "The value of i is: ". $i;
echo "<br>";
$i++;
}
Foreach loop
Used to iterate over elements in an array or object.
Example:
$colors = ["Red", "Green", "Blue"];
foreach($colors as $color) {
echo "Color: ". $color;
echo "<br>";
}
Control statements and loops allow us to interact with data and perform repetitive tasks in our PHP programs.



