4. PHP Decision Making and Loops
4. PHP Decision Making and Loops
In programming, decision-making structures allow you to control the flow of your code based on
certain conditions. Loops, on the other hand, enable repetitive tasks efficiently by iterating over
data or repeating actions until a condition is met. Below are detailed notes on both concepts, with
examples and real-world applications.
Definition
Syntax
if (condition) {
// Code to execute if condition is true
} elseif (another_condition) {
// Code to execute if the second condition is true
} else {
// Code to execute if all conditions are false
}
Example
$age = 20;
Real-World Application
Definition
Syntax
switch (expression) {
case value1 --
// Code to execute if expression == value1
break;
case value2 --
// Code to execute if expression == value2
break;
default --
// Code to execute if no case matches
}
Example
$day = "Monday";
switch ($day) {
case "Monday" --
echo "Start of the work week!";
break;
case "Friday" --
echo "Weekend is near!";
break;
default --
echo "Just another day.";
}
Real-World Application
• Menu Selection -- Display different actions based on the user's choice in a menu.
• Routing -- Handle different actions in a web application based on a user’s URL or input.
Loops in PHP
1. For Loop
Definition
The for loop is used when the number of iterations is known in advance. It consists of three
parts -- initialization, condition, and increment/decrement.
Syntax
Example
Real-World Application
2. While Loop
Definition
The while loop executes a block of code as long as the specified condition is true. It’s useful
when the number of iterations is not predetermined.
Syntax
while (condition) {
// Code to execute
}
Example
$count = 1;
Real-World Application
• User Input Validation -- Keep asking for correct input until valid data is provided.
• Downloading Files -- Check for download progress in a loop until complete.
3. Do...While Loop
Definition
The do...while loop is similar to the while loop but guarantees that the code block executes at
least once before the condition is checked.
Syntax
do {
// Code to execute
} while (condition);
Example
$count = 1;
do {
echo "Count is -- $count<br>";
$count++;
} while ($count <= 5);
Real-World Application
• User Login Attempts -- Ensure that a user is prompted for a password at least once.
• Game Scenarios -- Ensure an action like rolling dice occurs at least once.
4. Foreach Loop
Definition
The foreach loop is used to iterate over arrays, making it the best choice for handling
collections of data.
Syntax
Example
$fruits = ["Apple", "Banana", "Orange"];
Real-World Application
• Shopping Carts -- Display each item and its price in an online cart.
• Processing Form Data -- Loop through form inputs to save them into a database.