PHP Lesson 4: Control Structures (Decision Making and Loops)
Welcome back! So far, our code executes line by line from top to bottom. Control structures allow us to change that flow, enabling our programs to be smart, responsive, and efficient.
1. Decision Making: The if...else Statement
The if...else structure executes a block of code only if a specified condition is TRUE.
The Basic Structure
<?php
$score = 85;
if ($score >= 90) {
echo "You got an A! Excellent work.";
} elseif ($score >= 80) { // Check a secondary condition
echo "You got a B! Great job.";
} else { // If all other conditions are FALSE
echo "You need to study more.";
}
// Output: You got a B! Great job.
?>
Comparison Operators
To create conditions within the if statement, you use comparison operators:
| Operator | Name | Example (returns TRUE) |
== | Equal to | 5 == 5 |
!= | Not equal to | 5 != 10 |
> | Greater than | 10 > 5 |
< | Less than | 5 < 10 |
>= | Greater than or equal to | 5 >= 5 |
<= | Less than or equal to | 5 <= 10 |
2. Looping: Automating Repetitive Tasks
Loops are used to execute a block of code repeatedly as long as a certain condition is met. This is crucial for tasks like processing all items in an array or showing a list of database results.
The for Loop
The for loop is ideal when you know exactly how many times you want the loop to run.
Structure of a for loop:
Initialization: Set the counter's starting value (e.g.,
$i = 0).Condition: The loop continues as long as this condition is
TRUE(e.g.,$i < 5).Increment/Decrement: How the counter changes after each loop iteration (e.g.,
$i++means add 1).
<?php
echo "<h2>Counting to 5</h2>";
// $i++ is shorthand for $i = $i + 1
for ($i = 1; $i <= 5; $i++) {
echo "The count is: " . $i . "<br>";
}
/* Output:
The count is: 1
...
The count is: 5
*/
?>
The foreach Loop (Best for Arrays!)
The foreach loop is specifically designed to easily iterate (loop through) every item in an array. This is by far the most commonly used loop in PHP development.
A. Looping through Indexed Arrays:
<?php
$students = ["David", "Emily", "Frank"];
echo "<h2>Student List:</h2>";
foreach ($students as $name) {
echo "Student: " . $name . "<br>";
}
?>
B. Looping through Associative Arrays (Key and Value):
<?php
$person = [
"name" => "Alex",
"city" => "London",
"age" => 30
];
echo "<h2>User Details:</h2>";
// We get both the key (like "name") and the value (like "Alex")
foreach ($person as $key => $value) {
echo strtoupper($key) . ": " . $value . "<br>";
}
/* Output:
NAME: Alex
CITY: London
AGE: 30
*/
?>
3. Combining Structures
You will often use loops and decision structures together. For example, using a foreach loop to check a condition for every item in a list:
<?php
$products = [
"Laptop" => 1200,
"Mouse" => 25,
"Monitor" => 350
];
echo "<h2>Products Over $100:</h2>";
foreach ($products as $item => $price) {
if ($price > 100) {
echo $item . " costs $" . $price . "<br>";
}
}
/* Output:
Laptop costs $1200
Monitor costs $350
*/
?>
🚀 Your Fourth Challenge!
Create an indexed array called
$temperatureswith at least 5 integer values (e.g.,[15, 22, 18, 25, 19]).Use a
foreachloop to iterate through the array.Inside the loop, use an
ifstatement to check: if the temperature is greater than 20,echo"It's a warm day (Temp: [Temp])". Otherwise,echo"It's a cool day (Temp: [Temp])".
You now possess the foundational tools of almost any programming language! Next time, we will make your code organized and reusable by introducing Functions.
Comments
Post a Comment
Add your comment here.