PHP For Loops

PHP for loops are handy for running a block of code a set number of times. Learn how to use PHP for loops in this beginner tutorial.

PHP loops allow you to run the same chunk of code repeatedly. PHP features while and do...while loops, which are handy for general-purpose looping, and the more specialized for loop, which is useful when you want to run a chunk of code a known number of times.

This article explains how PHP for loops work, and shows you some practical for loop examples.

PHP for loop syntax

PHP for loops have the following general syntax:


for ( expression1; expression2; expression3 ) {
  // This code is run as long as expression2 is true
}

// This code is run after the loop finishes

You can see that for loops are more complex than while loops — whereas a while loop has 1 expression between the parentheses, a for loop has 3 expressions, separated by semicolons.

Here's how a for loop works:

  1. The first time through the loop, the PHP engine evaluates expression1. This expression is known as the initializer, and is usually used to set up a counter variable for the loop.
  2. At the start of each iteration of the loop, expression2 is tested. If it's true, the loop continues and the code inside the braces ({}) is run. If it's false the loop exits, and any code after the closing brace is run. expression2 is known as the loop test, and serves the same purpose as the single expression in a while loop.
  3. After each iteration, the PHP engine evaluates expression3. This expression is known as the counting expression, and is usually used to change the counter variable.

Some for loop examples

for loops are primarily designed to run a chunk of code a known number of times. Here's a simple example:


for ( $i = 1; $i <= 5; $i++ ) {
  echo "Counted to $i...<br />";
}

echo "Finished!";

When run, this code displays the following:


Counted to 1...
Counted to 2...
Counted to 3...
Counted to 4...
Counted to 5...
Finished!

You can see how the 3 expressions in a for loop make it easy to set up and increment a counter variable, $i, for looping a known number of times.

You don't have to count upwards though, as the following examples show:


// Count backwards from 5 to 1

for ( $i = 5; $i >= 1; $i-- ) {
  echo "$i...<br />";
}

echo "Finished!<br /><br />";

// Display all powers of 2 less than 40

for ( $num = 1; $num < 40; $num *= 2 ) {
  echo "$num...<br />";
}

echo "Finished!<br />";

The above code displays the following:


5...
4...
3...
2...
1...
Finished!

1...
2...
4...
8...
16...
32...
Finished!

A real-world example: generating passwords

Say you want to generate an 8-character random password for a user. A for loop is perfect here, since you know in advance how many times you want the loop to run (8 in this case):


$password = "";

for ( $i = 0; $i < 8; $i++ ) {
  $password .= chr ( rand ( 0, 25 ) + 97 );
}

echo "Your new password is: $password";

This displays something like:


Your new password is: fynqtfxs 

for loop expressions are optional

It's worth pointing out that each of the 3 expressions in a for loop is optional. (If you miss out the loop test expression then it defaults to true, making the loop continue forever.)

An example:


$num1 = 1;
$num2 = 5;

for ( ; $num1 <= $num2; $num1++ ) {
  echo "$num1...<br />";
}

echo "Finished!<br /><br />";

This code displays:


1...
2...
3...
4...
5...
Finished!

Here's an infinite for loop (it will keep running forever unless stopped in another way):


for ( ; ; )
{
  // This code keeps running forever
}

You've now seen how PHP for loops work. You've learned the for loop syntax, looked at some examples of for loops, and explored optional for loop expressions. Happy looping!

Learn PHP With Ease!

Written by Matt Doyle — ELATED's resident Web programming expert — Beginning PHP 5.3 is a complete introduction to PHP, covering everything in these tutorials and lots more besides. Find out how to:

  • Set up PHP on your computer
  • Use strings, arrays, functions and objects
  • Create interactive Web forms
  • Handle cookies and sessions
  • Work with files on the server
  • Build database-driven sites with MySQL
  • Send emails from your scripts
  • Create images on the fly with PHP
  • Work with regular expressions
  • Write robust, secure PHP applications

...and lots more!

“What a pleasure it's been spending hours and hours studying PHP with this magical book.” — Lulio, Florida
“The book is not only great for learning, but I find myself using it constantly as a reference as well!” — David A. Stoltz

Buy Beginning PHP 5.3 now from Amazon.comBeginning PHP 5.3 or Amazon.co.ukBeginning PHP 5.3.

Follow Elated

Related articles

Responses to this article

There are no responses yet.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page