OneBite.Dev - Coding blog in a bite size

Do A For Loop In PHP

Code snippet for how to Do A For Loop In PHP with sample and detail explanation

Mastering loops is a crucial skill in web development. One of the common types of loops in PHP is the ‘for’ loop, which allows us to execute a block of code a specified number of times. In this article, we will walk through how to write a ‘for’ loop in PHP.

Code snippet for ‘For’ loop in PHP

Consider the following basic example of a ‘for’ loop in PHP:

<?php
for ($i = 0; $i < 10; $i++) {
    echo $i;
}
?>

Code Explanation for ‘For’ loop in PHP

Let’s break down what’s happening in the provided code snippet:

  1. The ‘for’ loop begins with the keyword ‘for’. This introduces the loop structure.

  2. In the parentheses following the ‘for’ keyword, we have three separate expressions, separated by two semicolons.

    • The first expression is $i = 0, which is the initialisation. It sets up the counter variable ($i, in this case) to its starting value. This is executed only once at the beginning of the loop.

    • The second expression is $i < 10, which is the condition. The loop will keep iterating as long as this condition holds true. In this example, the loop will continue as long as the value of $i is less than 10.

    • The third expression is $i++, which is the incrementation. This modifies the counter variable in some way after each loop iteration. In this case, it simply increments the value of $i by 1 each time the loop runs.

  3. Inside the curly braces {} of the loop, we have the code block to be executed for each iteration. Here, we just have a simple echo command to print out the value of $i.

In conclusion, this ‘for’ loop outputs the numbers 0 through 9 (inclusive) to the screen. Understanding loops in PHP opens the door to more dynamic and efficient coding.

php