Loop it up: Unleash the power of for loops!
I use for loops way more than I use while loops. It seems like most of the time I’m reading items from a database: for loops are perfect for that. I tend to use while loops in Java programs where I need to execute some code until the program terminates; that’s not realistic in PHP. In web-programming, I almost exclusively use for and foreach loops.
In most programming languages, the for loop follows the following syntax:
for (exp_before; exp_before_loop_body; exp_after) { loop_body }
Once PHP encounters the for loop, it looks at the expression exp_before to initialize the necessary variables that are required by the loop. When we looked at while loops, we initialized the $i counter outside of the while loop. This is now done inside of the exp_before expression.
$i = 0; while(...) { }
for ($i = 0; ...) { }
Next, PHP looks at the expression exp_before_loop_body that comes before the for loop body but after the initialization step. This is where the conditional testing will be done. This is like the conditional statement inside of the while loop.
while ($i < 10) { }
for (...; $i < 10; ...) { }
If the expression is evaluated to true, it can enter the loop body and evaluate the content that’s inside of the loop body.
while ($i < 10) {
echo "Hello";
}
for (...; $i < 10; ...) {
echo "Hello";
}
Once all of the statements are executed inside of the loop body, PHP looks at the last expression inside of the for-loop (exp_after). Most of the time, this is where you would increment or decrement the counter variable that was initialized in exp_before. Again, let’s compare it to the while loop.
while (...) {
...
$i++;
}
for (...; ...; $i++) {
...
}
In order of execution:
- exp_before
- exp_before_loop_body
- loop_body
- exp_after
The simplest way to visualize this is by converting a while loop into a for loop.
<?php
$i = 0; // exp_before
while ( $i < 10 ) { // exp_before_loop_body
echo $i . "<br>"; // loop_body
$i++; // exp_after
}
for ( $i = 0; $i < 10; $i++ ) {
echo $i . "<br>";
}
?>
Both loops will do the same thing: display integers 0 through 9. Let’s walk through the for loop.
- PHP encounters the for keyword. It knows that this is a for loop.
- It checks the initialization phase. It sets $i = 0.
- It checks the conditional. Is $i < 10? Is 0 < 10? Yes. So, enter loop body.
- Execute echo statement. Prints 0.
- Increment $i. During the first iteration, increment $i from 0 to 1.
- Repeat 3 to 5 until $i equals 9. We’re not repeating 2 since that would reinitialize $i and would create an infinite loop.
- Once $i is incremented from 9 to 10, PHP checks to see if 10 is less than 10. Since 10 is not less than 10, the loop terminates. PHP continues executing code after the for loop’s closing curly brace.
We can loop through an array of items with the for loop. This is where the for loop shines.
$things_i_hate = [
"lists",
"repetition",
"entitlement",
"my job"
];
for ( $i = 0; $i < count($things_i_hate); $i++ ) {
echo $things_i_hate[$i] . "<br>";
}
?>
In the example above, we have an array of strings. To get the number of elements in the array, we use the count() function and we pass the array variable to it. Since arrays in PHP start at 0 and go up to the number of elements minus 1, the element count is a good upper bound. We can use the for loop to iterate through the array. Let’s look at it more logically.
- PHP creates the $things_i_hate variable and stores the array with 4 strings inside of it.
- It encounters the for keyword.
- PHP initializes $i to 0. Why 0? Because the first element in the array is at index 0.
- PHP gets the number of elements in the array with the help of the count($things_i_hate) function. The count() function returns 4.
- PHP tests to see whether $i is less than 4. During the first iteration, $i = 0, so $i is less than 4.
- PHP enters the loop body and echoes out $things_i_hate[ $i ]. During the first iteration, $i = 0, so the first element in the array is displayed.
- PHP increments $i. During the first iteration, it increments $i from 0 to 1.
- PHP repeats the process from 4 to 7.
- When $i is incremented from 3 to 4, PHP checks to see if $i is less than 4. Since 4 is not less than 4, PHP terminates. Elements at indices 0, 1, 2, and 3 are displayed.
You may be wondering what happens if you set the condition $i < 4 to $i ≤ 4. PHP would then attempt to echo out $things_i_hate[4], which does not exist. An Array Index OutOfBoundsException error would be thrown.
What if we wanted to display the elements in reverse? The for loop can do that too. We just have to change the logic a little.
<?php
$things_i_hate = [
"lists",
"repetition",
"entitlement",
"my job"
];
for ( $i = count($things_i_hate) - 1; $i >= 0; $i-- ) {
echo $things_i_hate[$i] . "<br>";
}
?>
This time, we’ll initialize the index to be the last element in the array. Since the count() function returns the number of elements in the array, this would put the index out of bounds if we attempted to call the last array element with that value. We need to subtract 1 to get to the last element. Remember, arrays start at 0. Once the initialization step is reached, PHP tests to see whether it reached the first element. It wants to display the first element, but it can’t go past it. That’s why we set the condition to $i ≥ 0. Once PHP executes the statement inside of the loop body, it decrements $i to move to the element before.
Although the for loop is great, PHP has an even better loop for looping through arrays called the foreach loop, which we’ll cover next time.
PHP Tutorial Series
Continue your learning with these articles
WHAT DO YOU DO WHILE DOING DO-WHILE LOOPS?
A regular while loop will skip over the loop body if the expression that’s evaluated is never true. But what if we need the contents of the body to be executed at least once? That’s what the do-while loop does for us.
Loop it up: Unleash the power of for loops!
I use for loops way more than I use while loops. It seems like most of the time I’m reading items from a database: for loops are perfect for that.
UNLEASH THE POWER OF EACH: EMBRACE THE FOREACH!
You can use the for loop to iterate through an array, but to really shine, you need to use the foreach loop. PHP allows you to foreach through arrays.