Sling Academy
Home/PHP/Mastering ‘for’ loops in PHP

Mastering ‘for’ loops in PHP

Last updated: January 09, 2024

Overview

PHP’s ‘for’ loop is a fundamental construct for iterating over ranges or arrays, enabling tasks from simple data listing to complex algorithm implementation. This tutorial provides an in-depth understanding, reinforced with practical examples taking you from basic to advanced usage.

Getting Started with ‘for’ loops

‘For’ loops in PHP offer a concise way to iterate over a block of code multiple times. The syntax is as follows:

for (init; condition; increment) {
    // Code to be executed for each iteration
}

Let’s explore this with a simple example:

<?php
for ($i = 0; $i < 5; $i++) {
    echo $i . '\n';
}
?>

This will output the numbers 0 to 4, each on a new line.

Looping Through Arrays

A common use of the ‘for’ loop is to traverse arrays:

<?php
$arr = array('apple', 'banana', 'cherry');
for ($i = 0; $i < count($arr); $i++) {
    echo $arr[$i] . '\n';
}
?>

This code goes through each element in the array and prints it. Notice the use of count to dynamically determine the loop’s bounds.

Nested ‘for’ loops

A ‘for’ loop can be nested inside another ‘for’ loop to handle multi-dimensional data. Here’s an example with a two-dimensional array:

<?php
$matrix = array(
    array(1, 2, 3),
    array(4, 5, 6),
    array(7, 8, 9)
);

for ($i = 0; $i < count($matrix); $i++) {
    for ($j = 0; $j < count($matrix[$i]); $j++) {
        echo $matrix[$i][$j] . ' ';
    }
    echo '\n';
}
?>

This will print each row of the matrix on a new line.

Advanced ‘for’ loop Techniques

Using ‘for’ loops, you can perform more complex operations. Let’s look at a few:

Range-Based ‘for’ loop

We can use the range() function to create an array representing a range of numbers:

<?php
foreach(range(0, 4) as $number) {
    echo $number . '\n';
}
?>

This will output numbers from 0 to 4, skipping the creation of an explicit array.

List Each Character in a String

We can iterate through the characters of a string with a ‘for’ loop like:

<?php
$str = 'hello';
for ($i = 0; $i < strlen($str); $i++) {
    echo $str[$i];
}
?>

This prints each character in the string ‘hello’ on a new line.

Custom Increment and Decrement

The third expression in a ‘for’ loop doesn’t have to be a simple increment. It can involve more complex operations and even function calls.

<?php
for ($i = 0; $i < 100; $i += rand(1, 10)) {
    // Do something with a non-uniform step size.
}
?>

In this snippet, the variable $i increments by a random number between 1 and 10 for each iteration.

Breaking Out of ‘for’ Loops

Sometimes you might want to exit a loop prematurely. Use break for this purpose:

<?php
for ($i = 0; $i < 10; $i++) {
    if ($i === 5) {
        break; // Exits the loop when $i is 5.
    }
    echo $i . '\n';
}
?>

The above code will stop executing once $i reaches 5.

Skipping Iterations with ‘continue’

Alternatively, you may wish to skip the rest of the current loop iteration and continue with the next one. Use the continue statement:

<?php
for ($i = 0; $i < 10; $i++) {
    if ($i === 5) {
        continue; // Skips this iteration when $i is 5.
    }
    echo $i . '\n';
}
?>

This will output all numbers from 0 to 9, except for 5.

Conclusion

‘For’ loops are a powerful aspect of PHP that can greatly enhance your code’s capabilities. From basic counter loops to advanced nested structures, understanding and utilizing ‘for’ loops effectively can streamline many programming tasks in PHP. Practice these concepts and always seek to understand the flow of iteration within your programs.

Next Article: Mastering ‘foreach’ loops in PHP

Previous Article: Mastering Try-Catch Statements in PHP

Series: Basic PHP Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array