Chapter 4: Control Structures and Loops: Managing Program Flow
In this chapter, we will explore control structures and loops in PHP, which allow us to manage the flow of our program. We will cover making decisions with if-else statements, using switch statements for multi-branch decisions, and working with various loop constructs.
4.1 Making decisions with if-else statements:
The if statement allows us to execute a block of code if a certain condition is true. It can be followed by an optional else statement to handle the case when the condition is false.
The elseif statement can be used to add additional conditions to check.
Example:
php
""
<?php
$age = 18;
if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are not eligible to vote.";
}
// Output: You are eligible to vote.
?>
4.2 Switch statements for multi-branch decisions:
The switch statement allows us to perform different actions based on different conditions or cases.
It provides an alternative to using multiple if statements.
Example:
php
""
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week";
break;
case "Friday":
echo "End of the week";
break;
default:
echo "Somewhere in between";
break;
}
// Output: Start of the week
?>
4.3 Looping constructs: while, do-while, for, and foreach:
Loops allow us to repeat a block of code multiple times until a certain condition is met.
The while loop executes a block of code as long as a condition is true. It checks the condition before each iteration.
The do-while loop is similar to the while loop, but it checks the condition after each iteration, ensuring that the block of code is executed at least once.
The for loop allows us to specify the initial value, condition, and increment or decrement in a single line.
The foreach loop is specifically designed for iterating over arrays or other iterable objects.
Example:
php
""
<?php
// while loop
$count = 1;
while ($count <= 5) {
echo $count . " ";
$count++;
}
// Output: 1 2 3 4 5
// do-while loop
$count = 1;
do {
echo $count . " ";
$count++;
} while ($count <= 5);
// Output: 1 2 3 4 5
// for loop
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
// Output: 1 2 3 4 5
// foreach loop
$fruits = array("apple", "banana", "orange");
foreach ($fruits as $fruit) {
echo $fruit . " ";
}
// Output: apple banana orange
?>
By following the explanations and examples in this chapter, you will gain a solid understanding of control structures and loops in PHP, allowing you to manage the flow of your program and execute code based on different conditions.
0 comments:
Post a Comment