FOR loops in PHP
In this article, we will go into more details in the for loop, but basically, they all behave the same. I will also through in some tricks and tips and what to be careful of when using loops.
Loops in PHP are used to execute a block of code a specific number of times.
It supports several loop types as follows:
- for — loops through a block of code a specified number of times.
- while — loops through a block of code if and as long as a specified condition is true.
- do…while — loops through a block of code once, then repeats the loop as long as a particular condition is true.
- foreach — is used to iterate over arrays or objects.
break
and continue
statements:
These statements can be used inside loops to change the flow of execution. The break
statement breaks out of the loop entirely, while the continue
statement skips to the next iteration of the loop.
FOR loop
In PHP, a for
loop, is a type of loop that allows you to execute a block of code a specific number of times. The syntax for a for
loop is as follows:
for (initialization; condition; increment) {
// code to be executed
}
/* example 1 */
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
/* example 2 */
for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo $i;
}
/* example 3 */
$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}
/* example 4 */
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
Here’s a breakdown of the different parts of a for
loop:
initialization
: This is where you set the initial value of the loop counter variable. This is typically done with an assignment statement, such as$i = 0;
.condition
: This is a boolean expression that is evaluated before each iteration of the loop. If the expression is true, the loop continues to execute. If it is false, the loop exits. For example,$i < 10;
means the loop will run as long as$i
is less than 10.increment
: This is an expression that is evaluated after each iteration of the loop. It typically updates the loop counter variable to move the loop closer to its exit condition. For example,$i++
increments$i
by 1 after each iteration.
Break out of a for loop
In PHP, breaking from a foreach
loop after a certain count is a simple process.
Using a if
statement to conditionally break
from the loop.
In this example:
- A counter variable is initialized to one when the loop starts;
- Inside the
for
loop, the counter is incremented using the post-increment operator ($i++
); - The loop is exited conditionally when the counter variable is greater than or equal to three, otherwise, the current item is output.
This results in the loop only executing for the first three times.
Using a if
statement to conditionally skip an element from processing in a loop:
The step is the same as above but in this case, the loop only skips one element and continues processing the rest.
Break/Continue an outer loop
In PHP, you can use the break
and continue
statements to control the flow of execution inside loops. However, if you want to break or continue an outer loop from within a nested loop, you can use the break
and continue
statements with a label.
Considering the code below:
Here when the conditions are met, so $i == 1
and $j === 1
then we skip that row and continue to the next one.
The result would be:
So breaking/continue works in the same way, the only difference is that break, will break out of the loop while continue will only skip that iteration.
NOTE: Using
continue
without an argument inside aswitch
statement behaves likebreak
(and raises a warning). Generally, you should avoid usingcontinue
insideswitch
(and usebreak
instead) unless it's to continue/skip to the next iteration of an outer loop.
// output: '1;skip;3;skip;Breaking switch + while;'
Optimizing PHP loops
When it comes to optimizing loops in PHP there are several ways to do that.
- Minimize the iterations. For example instead of looping through an array and checking each element if a particular element exists, use built-in functions such as:
in_array
orarray_search
orarray_key_exists
. - If you are iterating over arrays, use
foreach
instead offor
. This is becauseforeach
uses internal pointers to traverse the array, whereasfor
requires indexing and incrementing. - Pre-calculate loop conditions: If you need to calculate the length of an array or the number of iterations beforehand, do it outside the loop and store the value in a variable. This can save processing time by avoiding unnecessary calculations during each iteration of the loop.
- Use array
keys
instead ofvalues
: If you need to access both the key and value of an array element, it can be more efficient to use the keys rather than the values. This is because PHP arrays are implemented as hash tables, and accessing a key is faster than accessing a value. - Use break or continue: If you can exit the loop early based on certain conditions, use
break
to terminate the loop orcontinue
to skip to the next iteration. This can save processing time by avoiding unnecessary iterations. - Use pre-increment or pre-decrement operators: Using pre-increment or pre-decrement operators (
++$i
or--$i
) can be faster than using post-increment or post-decrement operators ($i++
or$i--
) because they don't require a copy of the variable. - Use the strict comparison operator: If you’re comparing values inside the loop, use the strict comparison operator (
===
) instead of the loose comparison operator (==
). This can prevent PHP from having to do type coercion on each comparison. - Avoid function calls inside the loop: Function calls can be expensive, so try to avoid calling functions inside the loop if possible. Instead, assign the result of the function call to a variable outside the loop.
- Use unset() to free memory: If you are iterating over a large array and modifying it, unset the elements that are no longer needed to free up memory. This can improve performance.
- Use the correct loop construct: Use the correct loop construct for the job. For example, use a
while
loop when you don't know the number of iterations in advance, or use afor
loop when you do.
Example 1: consider this code:
// Original for loop
for ($i = 0; $i < count($array); $i++) {
// Do something with $array[$i]
}
// Optimized for loop
$arrayCount = count($array);
for ($i = 0; $i < $arrayCount; $i++) {
// Do something with $array[$i]
}
Example 2: loop-invariant code. Which means the calculation of things inside the loop. This refers to things that can also be done outside the loop.
Consider the code below:
<?php
// Unoptimized code
$n = 100;
for ($i = 1; $i < 100; ++$i) {
for ($j = 1; $j < 100; ++$j) {
$somearray[$i][$j] = ($n * 100) + ($i * $n) + ($j * $n);
}
}
Inside our inner loop ($j), you will see values are put into a two-dimensional array using three added calculations: $n * 100
, $i * $n
, and $j * $n
. Of these three, $n * 100
will always be the same value because $n does not change and 100 is always 100. So let's fix it.
<?php
// Optimized code
$n = 100;
$n_mult_100 = $n * 100; # <===
for ($i = 0; $i < 100; ++$i) {
$i_mult_n = $i * $n; # <===
for ($j = 0; $j < 100; ++$j) {
$somearray[$i][$j] = $n_mult_100 + $i_mult_n + ($j * $n);
}
}
This new code has removed the loop invariance, thus making the script run faster.
Example 3: using foreach instead of for.
// Example 3: Unoptimized code
$fruits = array("apple", "banana", "orange");
for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i];
}
// Example 3: Optimized code
$fruits = array("apple", "banana", "orange");
foreach ($fruits as $fruit) {
echo $fruit;
}
Example 4: using break
or continue
.
// Optimized code
$fruits = array("apple", "banana", "orange");
foreach ($fruits as $fruit) {
if ($fruit == "banana") {
continue; // Skip iteration
}
echo $fruit;
}
Example 5: optimizing foreach
loops. In this example, we use a reference &$value
to the array value, which avoids creating a new copy of the value. We also use unset()
to remove any reference after the loop, to prevent any unintended side effects.
// Original foreach loop
foreach ($array as $value) {
// Do something with $value
}
// Optimized foreach loop
foreach ($array as &$value) {
// Do something with $value
}
unset($value);
The Handling of dangling array references we will tackle in a different article.
Feel free to Subscribe for more content like this 🔔, clap 👏🏻 , comment 💬 and share the article with anyone you’d like
And as it always has been, I appreciate your support, and thanks for reading.