Control Flow
Control flow statements allow your programs to make decisions and repeat actions. Instead of running code line by line, you can create programs that respond to different conditions and loop through data. This is where your code becomes truly dynamic!
What You'll Learn
- How to use if/else statements for decision making
- Comparison and logical operators
- Switch statements for multiple conditions
- While and for loops for repetition
- Break and continue statements
- Practical examples of control flow
If Statements
The if statement executes code only when a condition is true:
<?php
$age = 18;
if ($age >= 18) {
echo "You are an adult.\n";
}
// If-else
$temperature = 75;
if ($temperature > 80) {
echo "It's hot outside!\n";
} else {
echo "The weather is pleasant.\n";
}
// If-elseif-else
$score = 85;
if ($score >= 90) {
echo "Grade: A\n";
} elseif ($score >= 80) {
echo "Grade: B\n";
} elseif ($score >= 70) {
echo "Grade: C\n";
} elseif ($score >= 60) {
echo "Grade: D\n";
} else {
echo "Grade: F\n";
}
Comparison Operators
PHP provides several operators for comparing values:
<?php
$a = 10;
$b = 20;
$c = "10";
// Equal to (value)
echo "10 == 20: ";
var_dump($a == $b); // false
echo "10 == '10': ";
var_dump($a == $c); // true (loose comparison)
// Identical to (value and type)
echo "10 === '10': ";
var_dump($a === $c); // false (strict comparison)
// Not equal to
echo "10 != 20: ";
var_dump($a != $b); // true
// Not identical to
echo "10 !== '10': ";
var_dump($a !== $c); // true
// Greater than / Less than
echo "10 > 20: ";
var_dump($a > $b); // false
echo "10 < 20: ";
var_dump($a < $b); // true
// Greater than or equal to
echo "10 >= 10: ";
var_dump($a >= 10); // true
// Less than or equal to
echo "10 <= 5: ";
var_dump($a <= 5); // false
Best Practice: Use strict comparison (=== and !==) to avoid unexpected type coercion.
Logical Operators
Combine multiple conditions with logical operators:
<?php
$age = 25;
$hasLicense = true;
$hasInsurance = true;
// AND operator (&&)
if ($age >= 18 && $hasLicense) {
echo "You can drive!\n";
}
// OR operator (||)
$isWeekend = false;
$isHoliday = true;
if ($isWeekend || $isHoliday) {
echo "No work today!\n";
}
// NOT operator (!)
$isRaining = false;
if (!$isRaining) {
echo "No umbrella needed!\n";
}
// Combining multiple conditions
if ($age >= 21 && $hasLicense && $hasInsurance) {
echo "You can rent a car!\n";
}
if (($age >= 18 && $age < 65) || $hasLicense) {
echo "Special offer available!\n";
}
Switch Statements
Switch statements are useful when comparing one value against multiple possibilities:
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week\n";
break;
case "Friday":
echo "Almost weekend!\n";
break;
case "Saturday":
case "Sunday":
echo "It's the weekend!\n";
break;
default:
echo "It's a regular weekday\n";
break;
}
// Switch with numbers
$status = 2;
switch ($status) {
case 1:
echo "Status: Pending\n";
break;
case 2:
echo "Status: Approved\n";
break;
case 3:
echo "Status: Rejected\n";
break;
default:
echo "Status: Unknown\n";
break;
}
Note: Don't forget the break statement! Without it, PHP will continue executing the next cases.
While Loops
While loops repeat code as long as a condition is true:
<?php
// Basic while loop
$count = 1;
while ($count <= 5) {
echo "Count: $count\n";
$count++;
}
// Countdown example
$countdown = 5;
echo "Countdown: ";
while ($countdown > 0) {
echo "$countdown... ";
$countdown--;
}
echo "Liftoff!\n";
// Processing items
$balance = 100;
$items = 0;
while ($balance >= 10) {
$balance -= 10;
$items++;
}
echo "Purchased $items items, remaining balance: $$balance\n";
Do-While Loops
Do-while loops execute at least once before checking the condition:
<?php
$number = 1;
do {
echo "Number: $number\n";
$number++;
} while ($number <= 3);
// Runs at least once even if condition is false
$value = 10;
do {
echo "This runs once: $value\n";
} while ($value < 5); // Condition is false, but loop ran once
For Loops
For loops are perfect when you know how many times to repeat:
<?php
// Basic for loop
for ($i = 1; $i <= 5; $i++) {
echo "Iteration $i\n";
}
// Counting backwards
for ($i = 10; $i >= 1; $i--) {
echo "$i ";
}
echo "\n";
// Different increments
for ($i = 0; $i <= 20; $i += 5) {
echo "$i ";
}
echo "\n";
// Multiplication table
$number = 7;
echo "Multiplication table for $number:\n";
for ($i = 1; $i <= 10; $i++) {
$result = $number * $i;
echo "$number × $i = $result\n";
}
Break and Continue
Control loop execution with break and continue:
<?php
// Break - exit the loop entirely
echo "Using break:\n";
for ($i = 1; $i <= 10; $i++) {
if ($i === 5) {
break; // Stop when i is 5
}
echo "$i ";
}
echo "\n\n";
// Continue - skip to next iteration
echo "Using continue:\n";
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 === 0) {
continue; // Skip even numbers
}
echo "$i "; // Only odd numbers are printed
}
echo "\n\n";
// Practical example: finding a value
$numbers = [10, 20, 30, 40, 50];
$target = 30;
$found = false;
foreach ($numbers as $num) {
if ($num === $target) {
echo "Found $target!\n";
$found = true;
break;
}
}
if (!$found) {
echo "Not found\n";
}
Foreach Loops
Foreach loops are perfect for iterating over arrays:
<?php
// Simple array iteration
$fruits = ["Apple", "Banana", "Orange", "Mango"];
foreach ($fruits as $fruit) {
echo "- $fruit\n";
}
echo "\n";
// With index
foreach ($fruits as $index => $fruit) {
$position = $index + 1;
echo "$position. $fruit\n";
}
echo "\n";
// Associative arrays
$person = [
"name" => "Alice",
"age" => 25,
"city" => "New York"
];
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
Try It Yourself
Practice control flow with these exercises:
<?php
// 1. Check if a number is positive, negative, or zero
$number = 15;
if ($number > 0) {
echo "$number is positive\n";
} elseif ($number < 0) {
echo "$number is negative\n";
} else {
echo "$number is zero\n";
}
// 2. Print even numbers from 1 to 20
echo "Even numbers: ";
for ($i = 2; $i <= 20; $i += 2) {
echo "$i ";
}
echo "\n";
// 3. Calculate sum of numbers 1 to 10
$sum = 0;
for ($i = 1; $i <= 10; $i++) {
$sum += $i;
}
echo "Sum of 1 to 10: $sum\n";
// 4. FizzBuzz (classic programming challenge)
for ($i = 1; $i <= 15; $i++) {
if ($i % 15 === 0) {
echo "FizzBuzz ";
} elseif ($i % 3 === 0) {
echo "Fizz ";
} elseif ($i % 5 === 0) {
echo "Buzz ";
} else {
echo "$i ";
}
}
echo "\n";
// 5. Find the largest number
$numbers = [23, 67, 34, 89, 12, 56];
$largest = $numbers[0];
foreach ($numbers as $num) {
if ($num > $largest) {
$largest = $num;
}
}
echo "Largest number: $largest\n";
// Try creating your own control flow patterns!
Key Takeaways
- Use
if,elseif, andelsefor decision making - Use
===for strict comparison (checks value and type) - Combine conditions with
&&(AND),||(OR), and!(NOT) switchstatements are good for comparing one value against many optionswhileloops repeat while a condition is trueforloops are perfect when you know the iteration countforeachloops are ideal for arrays- Use
breakto exit loops andcontinueto skip iterations
Next Steps
In the next lesson, we'll dive into arrays and objects - PHP's powerful data structures for organizing and managing complex data. You'll learn how to work with collections of values and create structured data types.
Pro Tip: Practice by solving small problems! Try writing a program that validates user input, generates patterns with loops, or processes lists of data. The more you practice control flow, the more natural it becomes. Don't be afraid to combine different control structures to solve complex problems.