Mastering PHP Loops: A Comprehensive Guide
Loops are fundamental in PHP, enabling developers to execute repetitive tasks efficiently. Whether iterating over arrays, executing a block of code multiple times, or processing large datasets, loops help streamline code execution. In this guide, we will cover the different types of loops in PHP and provide practical examples for each.
PHP Loop Types
Loop Type | Syntax | Example |
---|---|---|
for |
for (init; condition; increment) { // code } |
for ($i = 1; $i <= 5; $i++) { echo $i; } |
while |
while (condition) { // code } |
$count = 1; while ($count <= 5) { echo $count; $count++; } |
do...while |
do { // code } while (condition); |
$count = 1; do { echo $count; $count++; } while ($count <= 5); |
foreach |
foreach ($array as $value) { // code } |
$fruits = ["Apple", "Banana"]; foreach ($fruits as $fruit) { echo $fruit; } |
1. for
Loop
The for
loop is commonly used when the number of iterations is known beforehand. It consists of an initialization, a condition, and an increment/decrement statement.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute
}
Example:
for ($i = 1; $i <= 5; $i++) {
echo "Iteration: $i \n";
}
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
When to Use
- When you need to iterate a specific number of times
- When you need a counter variable
- For mathematical operations requiring sequence generation
Yêu cầu đăng nhập
Vui lòng đăng nhập để truy cập nội dung này
Additional Resources
Course Guide
Comprehensive PDF guide with examples
GitHub Repository
Example code for all lessons
Discussion
Have a question about this lesson? Post it here and get answers from instructors and peers.