PHP - For Loop

Flowchart of "for" Loop

Before we dive into the syntax and examples, let's visualize how a for loop works. A for loop is like a conveyor belt that moves through a set of instructions. It starts with an initial condition, checks if it meets the end condition, and then executes the code block inside it. Once the code block is executed, it updates the counter and repeats the process until the end condition is no longer met.

PHP - For Loop

st=>start: 開始
e=>end: 結束
op1=>operation: 初始化計數器
cond=>condition: 檢查結束條件
op2=>operation: 更新計數器
op3=>operation: 執行代碼塊
cond2=>condition: 是否達到結束條件?
op4=>operation: 未達到,返回op2
op5=>operation: 達到,前往結束

st->op1->cond
cond(yes)->op3->op2->cond2
cond2(no)->op4->op2
cond2(yes)->op5->e

Syntax of "for" Loop

The basic syntax of a for loop in PHP is as follows:

for (initialization; condition; increment/decrement) {
// code to be executed
}
  • Initialization: This is where you initialize your counter variable.
  • Condition: This is the condition that must be true for the loop to continue. If it's false, the loop will stop.
  • Increment/Decrement: This is where you update your counter. You can increase or decrease it based on your requirements.

Example

Let's start with a simple example that prints numbers from 1 to 5 using a for loop.

<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
?>

In this example, we initialize $i to 1, check if $i is less than or equal to 5, and then increment $i by 1 after each iteration. The echo statement prints the value of $i followed by a space.

An Infinite "for" Loop

Be careful when writing loops, as an infinite loop can crash your program or make it unresponsive. Here's an example of an infinite loop:

<?php
for (;;) {
echo "This loop will run forever!";
}
?>

This loop has no initialization, condition, or increment/decrement, so it will keep running indefinitely. To stop it, you would need to manually interrupt the execution, such as by pressing Ctrl + C in the terminal.

A Decrementing "for" Loop

A decrementing for loop is similar to an incrementing one, but instead of increasing the counter, it decreases it. Here's an example that counts down from 5 to 1:

<?php
for ($i = 5; $i >= 1; $i--) {
echo $i . " ";
}
?>

Using the "for…endfor" Construct

PHP also provides a shorthand notation for for loops using the foreach construct. However, since our focus is on the traditional for loop, we'll stick to that for now.

Iterating an Indexed Array Using "for" Loop

You can use a for loop to iterate over an indexed array, accessing each element by its index. Here's an example:

<?php
$fruits = array("apple", "banana", "cherry");

for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . " ";
}
?>

In this example, we use the count() function to determine the number of elements in the $fruits array and then iterate over each element using its index.

Iterating an Associative Array Using "for" Loop

When working with associative arrays, you can use a for loop to iterate over both keys and values. Here's an example:

<?php
$students = array(
"Alice" => 25,
"Bob" => 27,
"Charlie" => 22
);

foreach ($students as $name => $age) {
echo "$name is $age years old.<br>";
}
?>

In this example, we use the foreach construct to iterate over the $students associative array. The $name variable holds the key (student name), and the $age variable holds the value (student age). We then print out each student's name and age.

Using Nested "for" Loops in PHP

Sometimes, you may need to use nested for loops to perform more complex tasks. Here's an example that prints a multiplication table:

<?php
for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= 5; $j++) {
echo $i * $j . "\t";
}
echo "<br>";
}
?>

In this example, the outer loop iterates over the rows (from 1 to 5), and the inner loop iterates over the columns (also from 1 to 5). The product of the row and column numbers is printed, creating a multiplication table.

That's it for our introduction to for loops in PHP! Remember, practice makes perfect, so try to write some code and experiment with different scenarios. Happy coding!

Credits: Image by storyset