Thursday, May 16, 2024

PHP Syntax: For Loop Basics

The for loop allows iteration for a fixed number of times.

The basic for loop syntax is as follows:

for (initialization; condition; incrementor) {

The initialization defines the loop variable and its initial value (such as $i=1). The loop will continue to iterate while the conditional expression evaluates as true (like $i<10). Each time the loop is executed, the incrementer code is executed. (The code $i++ would increment the loop variable $i by one; $i=$i*2 would double the loop variable $i each iteration.) We can put these together in a simple example: for ($i=1; $i<=10; $i+=2) { echo "$i "; }

This code would generate the output “1 3 5 7 9” since the variable $i starts at 1 and increments by two each loop until it is no longer less than or equal to 10.

Quinn McHenry
Quinn McHenry
Quinn was one of the original co-founders of Tech-Recipes. He is currently crafting iOS applications as a senior developer at Small Planet Digital in Brooklyn, New York.


Please enter your comment!
Please enter your name here

Most Popular


Recent Comments

error: Content is protected !!