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) {
code;
}

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.
RELATED ARTICLES

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments

Cleveland Furia on How to Clear Google Activity
Sid Wohlfarth on How to Clear Google Activity
Riley Magsayo on How to Clear Google Activity
สมัครรับเครดิตฟรี ทันที on How to improve Remote Desktop Protocol Performance
Neal Wangstad on How to Clear Google Activity
Slavcho Andov on How to install Ubuntu
Slavcho Andov on How to fix bad sectors
Sheraz Ali on How to Backup Android