Evaluating expressions in for-loops

March 25th, 2005. Tagged: PHP certification

The usual syntax of a for-loop is
< ?php
for($i = 0; $i < 10; $i++){
// do your thing


  1. $i = 0 is evaluated once before the loop starts
  2. $i < 10 is the condition of the loop, it's executed the number of times the loop executes plus 1. Why plus 1? Well the plus 1 is just to check we're at the end of the loop and no more looping is needed. In this example, this expression will be evaluated 11 times
  3. $i++ is an expression that executes after everything in the brackets is executed, i.e. at the end of each iteration. So in our example it's executed 10 times

The three expressions described above can be also function calls or something else, they are not necessarily always used as in the example above. Consider the next example as an illustration of how other functions can be called. All these functions print a line, so executing this will give you a visual idea what is executed, when and how many times.
< ?php
function start(){
echo '
return 0;
function condition($i){
echo '
condition: ' . $i;
return 10;
function increment(&$i){
echo '
increment: ' . $i;
for ($i = start(); $i < condition($i); increment($i)){
// do nothing
The loop in this example is doing exactly the same as the first loop, only it's defined fancier, using functions and all the three functions print a line. Here's what the output of the script would be:

condition: 0
increment: 0
condition: 1
increment: 1
condition: 2
increment: 2
condition: 3
increment: 3
condition: 4
increment: 4
condition: 5
increment: 5
condition: 6
increment: 6
condition: 7
increment: 7
condition: 8
increment: 8
condition: 9
increment: 9
condition: 10

So just a word of caution - in the conditions, be careful not to you use potentially slow functions or expressions that return the same value every time they're exeuted, as they are going to be needlessly executed the loop count plus 1 times.

As a quick example:
< ?php
// not good
for ($i = 0; $i < 100*99%98+189*345/2*56-1; $i++) {
echo $i;
// better
$boundary = 100*99%98+189*345/2*56-1;
for ($i = 0; $i < $boundary; $i++) {
echo $i;

Tell your friends about this post: Facebook, Twitter, Google+

Sorry, comments disabled and hidden due to excessive spam. Working on restoring the existing comments...

Meanwhile, hit me up on twitter @stoyanstefanov