• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / PHP / PHP For Loops

PHP For Loops

24 August 2009 / Leave a Comment

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!

Filed Under: PHP Tagged With: optional for loop expressions, password generator, php for loop examples, php for loop syntax, php for loops

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits