About Lesson
Control Flow:
Control flow refers to the order in which statements are executed in a program. In PHP, you can control the flow of your code using various control structures:
1. Conditional Statements:
- `if` statement: Executes a block of code if a condition is true.
- `else` statement: Executes a block of code if the previous `if` condition is false.
Example:
PHP
$condition = true;
if ($condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
- `elseif` statement: Executes a block of code if the previous `if` condition is false, but its own condition is true.
Example:
PHP
$score = 75;
if ($score >= 90) {
echo "Excellent";
} elseif ($score >= 70) {
echo "Good";
} else {
echo "Needs Improvement";
}
- `switch` statement: Allows you to select one of many blocks of code to be executed based on different conditions.
Example:
PHP
$day = "Monday";
switch ($day) {
case "Monday":
echo "It's Monday!";
break;
case "Friday":
echo "It's Friday!";
break;
default:
echo "It's another day.";
}
2. Looping Statements:
- `for` loop: Executes a block of code a specific number of times.
Example:
PHP
for ($i = 0; $i< 5; $i++) {
//code to repeat
echo $i;
}
- `while` loop: Executes a block of code as long as a condition is true.
Example:
PHP
$counter = 0;
while ($counter < 5) {
// Code to repeat
echo $counter;
$counter++;
}
- `do-while` loop: Executes a block of code at least once, and then repeats as long as a condition is true.
Example:
PHP
$counter = 0;
do {
// Code to repeat
echo $counter;
$counter++;
} while ($counter < 5);
- `foreach` loop: Iterates over each element in an array or collection.
Example:
PHP
$colors = array("Red", "Green", "Blue");
foreach ($colors as $color) {
// Code to repeat for each element
echo $color;
}
- Branching Statements:
- `break` statement: Terminates the execution of a loop or switch statement.
Example:
PHP
for ($i = 0; $i< 10; $i++) {
if ($i == 5) {
break; // Exit the loop when $i is 5
}
echo $i;
}
- `continue` statement: Skips the current iteration of a loop and moves to the next iteration.
Example:
PHP
for($i=0;$i<10;$i++){
if ($i == 5) {
continue; // Skip the rest of the loop when $i is 5
}
echo $i;
}
- `return` statement: Terminates the execution of a function and returns a value.
Example:
PHP
function multiply($a, $b) {
return $a * $b;
}
These control flow structures allow you to create dynamic and flexible PHP scripts by controlling the flow of execution based on conditions and iterations.