PHP Program to Demonstrate Conditions and loops
Learn PHP step by step.
All about PHP - Conditions and loops
Jan 29, 2026
## Chapter 9: Conditions and loops
**Think of conditions as decision-makers and loops as repetitive workers - they control the flow of your program!**
**Goal:** Make decisions and repeat work in a readable way.
### Conditions - Making Decisions Like a Human
**Conditions are like asking questions - if the answer is yes, do this, otherwise do that!**
```php
<?php
$age = 17;
if ($age >= 18) {
echo "Adult";
} else {
echo "Minor";
}
```
**Visual Diagram: Decision Making Flow**
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Decision Making Process β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β βββββββββββββββ β
β β Question β β
β β "Is age β₯ 18?" β β
β ββββββββ¬βββββββ β
β β β
β ββββββ΄βββββ β
β β YES β βββββββββββββββ β
β β β β NO β β
β βΌ β β β β
β βββββββββ β βΌ β β
β β Adult β ββββββ¬βββββββββββββββ β
β β β β β
β βββββββββ β β
β β β β
β ββββββββ¬ββββββββ β
β β β
β βΌ β
β βββββββββββββββ β
β β Continue β β
β β Program β β
β βββββββββββββββ β
β β
β **Like a traffic light - choose your path!** β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### Real-World Condition Examples
#### Example 1: Temperature Checker
```php
<?php
$temperature = 25;
if ($temperature > 30) {
echo "It's hot outside! ";
} elseif ($temperature > 20) {
echo "Perfect weather! ";
} elseif ($temperature > 10) {
echo "A bit cool!";
} else {
echo "It's cold!";
}
?>
```
#### Example 2: Login System
```php
<?php
$username = "admin";
$password = "secret123";
$isActive = true;
if ($username === "admin" && $password === "secret123" && $isActive) {
echo "Welcome, Admin!";
} elseif ($username === "admin" && $password === "secret123" && !$isActive) {
echo "Account is disabled. Contact support.";
} else {
echo "Invalid username or password.";
}
?>
```
#### Example 3: Grade Calculator
```php
<?php
$score = 85;
if ($score >= 90) {
$grade = "A";
$message = "Excellent work!";
} elseif ($score >= 80) {
$grade = "B";
$message = "Good job!";
} elseif ($score >= 70) {
$grade = "C";
$message = "Keep improving!";
} elseif ($score >= 60) {
$grade = "D";
$message = "Need more effort!";
} else {
$grade = "F";
$message = "Please retake the course!";
}
echo "Score: $score - Grade: $grade - $message";
?>
```
### Switch Statements - Multiple Choice Questions
**Switch is like a multiple choice test - pick one option from many!**
```php
<?php
$role = "admin";
switch ($role) {
case "admin":
echo "All access";
break;
case "editor":
echo "Write access";
break;
case "viewer":
echo "Read access";
break;
default:
echo "No access";
}
?>
```
**Visual Diagram: Switch Statement Flow**
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Switch Statement Flow β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β βββββββββββββββ β
β β $role = β β
β β "admin" β β
β ββββββββ¬βββββββ β
β β β
β ββββββ΄βββββ¬ββββββββββββββ¬ββββββββββββββ¬ββββββββββββββ β
β β case β case β case β default β β
β β "admin" β "editor" β "viewer" β β β
β β β β β β β
β βΌ βΌ βΌ βΌ βΌ β
β βββββββββ βββββββββ βββββββββ βββββββββ βββββββ
β β"All β β"Writeβ β"Read β β"No β β ββ
β βaccess"β βaccess"β βaccess"β βaccess"β β ββ
β βββββββββ βββββββββ βββββββββ βββββββββ βββββββ
β β β β β β β
β βββββββββββ΄ββββββββββββββ΄ββββββββββββββ΄ββββββββββββββ β
β β β
β βΌ β
β ββββββββββββββββ β
β β break β β
β β (exit switch)β β
β ββββββββββββββββ β
β β β
β βΌ β
β ββββββββββββββββ β
β β Continue β β
β β Program β β
β ββββββββββββββββ β
β β
β **Like a train station - pick your track!** β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### Match Expressions - Modern PHP (PHP 8+)
**Match is like switch but smarter - it returns a value directly!**
```php
<?php
$role = "editor";
$access = match ($role) {
"admin" => "all",
"editor" => "write",
"viewer" => "read",
default => "none"
};
echo "Your access level: $access";
?>
```
**The difference between switch and match:**
```php
<?php
// Switch - needs echo and break
switch ($role) {
case "admin":
echo "all";
break;
}
// Match - returns value directly
$access = match ($role) {
"admin" => "all",
default => "none"
};
?>
```
### Loops - Repetitive Workers
**Loops are like telling PHP: "Keep doing this until I say stop!"**
#### For Loop - Counting Repetitions
```php
<?php
// Count from 1 to 5
echo "Counting with for loop:n";
for ($i = 1; $i <= 5; $i++) {
echo "Number: $in";
}
// Count backwards
echo "nCounting backwards:n";
for ($i = 5; $i >= 1; $i--) {
echo "Number: $in";
}
?>
```
#### While Loop - Keep Going While True
```php
<?php
// Count with while loop
$count = 1;
echo "Counting with while loop:n";
while ($count <= 5) {
echo "Number: $countn";
$count++;
}
// User input validation
echo "nGuess the number (1-10): ";
$guess = 0;
$secretNumber = 7;
while ($guess != $secretNumber) {
$guess = rand(1, 10); // Simulate user input
echo "You guessed: $guessn";
if ($guess < $secretNumber) {
echo "Too low! Try again.n";
} elseif ($guess > $secretNumber) {
echo "Too high! Try again.n";
}
}
echo " Correct! The number was $secretNumber!";
?>
```
#### Foreach Loop - Going Through Collections
```php
<?php
// Loop through array
$colors = ["red", "green", "blue", "yellow"];
echo "Available colors:n";
foreach ($colors as $color) {
echo "- $colorn";
}
// Loop through associative array
$person = ["name" => "Sarah", "age" => 25, "city" => "New York"];
echo "nPerson details:n";
foreach ($person as $key => $value) {
echo ucfirst($key) . ": $valuen";
}
?>
```
### Loop Control - Break and Continue
**Sometimes you need to skip items or stop early!**
```php
<?php
// Skip even numbers
echo "Odd numbers only:n";
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
continue; // Skip even numbers
}
echo "$i ";
}
// Stop when we find what we're looking for
echo "nnFinding first multiple of 7:n";
for ($i = 1; $i <= 20; $i++) {
if ($i % 7 == 0) {
echo "Found it: $i!";
break; // Stop the loop
}
echo "Checking $i... ";
}
?>
```
### Nested Loops - Loops Inside Loops
**Like a calendar - days inside weeks inside months!**
```php
<?php
// Multiplication table
echo "Multiplication Table:n";
for ($row = 1; $row <= 5; $row++) {
for ($col = 1; $col <= 5; $col++) {
$result = $row * $col;
echo sprintf("%3d", $result) . " ";
}
echo "n";
}
// Pattern printing
echo "nTriangle Pattern:n";
for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo "* ";
}
echo "n";
}
?>
```
### Common Loop Mistakes (And How to Fix Them!)
| Mistake | What Happens | Fix It Like This |
|---------|-------------|------------------|
| **Infinite loop** | Program never stops | Make sure loop condition can become false |
| **Off-by-one error** | Loop runs one too many/few times | Check your start and end conditions |
| **Forgetting to increment** | While loop never ends | Always update loop variables |
| **Wrong loop type** | Confusing code | Use `for` for counting, `foreach` for arrays, `while` for conditions |
### Practice Exercises
**Try these to master conditions and loops:**
1. **FizzBuzz Challenge:**
```php
<?php
// Print numbers 1-100, but:
// - If divisible by 3, print "Fizz"
// - If divisible by 5, print "Buzz"
// - If divisible by both, print "FizzBuzz"
for ($i = 1; $i <= 100; $i++) {
if ($i % 3 == 0 && $i % 5 == 0) {
echo "FizzBuzz ";
} elseif ($i % 3 == 0) {
echo "Fizz ";
} elseif ($i % 5 == 0) {
echo "Buzz ";
} else {
echo "$i ";
}
}
?>
```
2. **Password Validator:**
```php
<?php
$password = "MyPass123!";
$hasMinLength = strlen($password) >= 8;
$hasUpper = $password !== strtolower($password);
$hasLower = $password !== strtoupper($password);
$hasNumber = preg_match("/[0-9]/", $password);
$hasSpecial = preg_match("/[!@#$%^&*]/", $password);
if ($hasMinLength && $hasUpper && $hasLower && $hasNumber && $hasSpecial) {
echo "Strong password!";
} else {
echo "Weak password. Missing: ";
if (!$hasMinLength) echo "min length ";
if (!$hasUpper) echo "uppercase ";
if (!$hasLower) echo "lowercase ";
if (!$hasNumber) echo "number ";
if (!$hasSpecial) echo "special char";
}
?>
```
3. **Number Guessing Game:**
```php
<?php
$secretNumber = rand(1, 100);
$attempts = 0;
$maxAttempts = 7;
echo "I'm thinking of a number between 1 and 100.n";
while ($attempts < $maxAttempts) {
$guess = rand(1, 100); // Simulate user input
$attempts++;
echo "Attempt $attempts: You guessed $guessn";
if ($guess == $secretNumber) {
echo " Correct! You found it in $attempts attempts!";
break;
} elseif ($guess < $secretNumber) {
echo "Too low! ";
} else {
echo "Too high! ";
}
if ($attempts == $maxAttempts) {
echo "nGame over! The number was $secretNumber.";
}
}
?>
```
### Key Takeaways
- **Conditions make decisions** - use `if/elseif/else` for logic
- **Switch is for multiple choices** - cleaner than many if statements
- **Match returns values directly** - modern PHP alternative to switch
- **Loops repeat actions** - `for` for counting, `while` for conditions, `foreach` for arrays
- **Break and continue control loops** - skip items or exit early
**Remember:** Conditions and loops are PHP's way of thinking and working - master them and your programs become smart and efficient!**
default => "read"
};
echo $access;
```
---
## Conclusion
In this article, we explored the core concepts of All about PHP - Conditions and loops. Understanding these fundamentals is crucial for any developer looking to master this topic.
## Frequently Asked Questions (FAQs)
**Q: What is All about PHP - Conditions and loops?**
A: All about PHP - Conditions and loops is a fundamental concept in this programming language/topic that allows developers to perform specific tasks efficiently.
**Q: Why is All about PHP - Conditions and loops important?**
A: It helps in organizing code, improving performance, and implementing complex logic in a structured way.
**Q: How to get started with All about PHP - Conditions and loops?**
A: You can start by practicing the basic syntax and examples provided in this tutorial.
**Q: Are there any prerequisites for All about PHP - Conditions and loops?**
A: Basic knowledge of programming logic and syntax is recommended.
**Q: Can All about PHP - Conditions and loops be used in real-world projects?**
A: Yes, it is widely used in enterprise-level applications and software development.
**Q: Where can I find more examples of All about PHP - Conditions and loops?**
A: You can check our blog section for more advanced tutorials and use cases.
**Q: Is All about PHP - Conditions and loops suitable for beginners?**
A: Yes, our guide is designed to be beginner-friendly with clear explanations.
**Q: How does All about PHP - Conditions and loops improve code quality?**
A: By providing a standardized way to handle logic, it makes code more readable and maintainable.
**Q: What are common mistakes when using All about PHP - Conditions and loops?**
A: Common mistakes include incorrect syntax usage and not following best practices, which we've covered here.
**Q: Does this tutorial cover advanced All about PHP - Conditions and loops?**
A: This article covers the essentials; stay tuned for our advanced series on this topic.