Hudzilla.org - the homepage of Paul Hudson
Contents > Introducing PHP > How PHP is written Wish List | Report Bug | About Me ]

2.6.10     Loops

This is NOT the latest copy of this book; click here for the latest version.

There are four ways to make code loop in PHP so that you can perform repetitive actions, and each work in different ways. In practice, only three of the four are used regularly, but you need to at least be aware of all four.

The first loop type is called a while loop, and can be thought of as an if statement that is evaluated repeatedly until it fails. In pseudocode it looks like this:

while (condition is true) {
    do code
}

Notice that again PHP uses code blocks to represent the extent of our loop - while loops start with an opening brace { and finish with a close brace } to tell PHP clearly which lines of code should be looped through.

Like if statements, you can put whatever conditions you like into while loops, however it is crucial that you change the value of the condition with each loop. Consider this piece of code:

<?php
    
while (1 == 1) {
        
// do stuff
    
}
?>

1 is always, always going to be equal to 1, which means this while loop will just whiz around in circles perpetually. This is called an infinite loop - a loop that will not exit because its condition will always be met - and they tend to drag your computer to a halt very quickly. Having said that, infinite loops can be useful - we'll look at those situations soon.

"While" loops are most often used to increment a list where there is no known limit to the number of iterations of the loop. For example:

<?php
    
while(there are still rows to read from a database) {
        
read in row;
        
move to the next to row;
    }
?>

A more common form of loop is the "for" loop, and is slightly more complicated. A for loop has three parts - a declaration, a condition, and an action - as well as a loop counter variable that tracks the number of times the loop code has been executed (the number of iterations). The declaration is where the loop counter variable is declared and set to a starting value, the condition is where the loop variable counter is checked against a value, and the action is the action to take at the end of each iteration to change the loop counter.

Here is how a for loop looks in PHP:

<?php
    
for ($i = 1; $i < 10; $i = $i + 1) {
        print
"Number $i\n";
    }
?>

As you can see, the for loop has the three distinct parts separated by a semi-colon each. Firstly, for our declaration, we set the variable $i to 1. Our condition, the second of the three parts in the for loop, is that the loop will execute if $i is less than 10. Finally, the action is that we add 1 to the value of $i every loop iteration - that is, every time the loop code is executed. So, a for loop is made up of a declaration, a condition, and an action.

Therefore, what this script does is to count from 1 to 10, outputting text along the way. Note that it will not actually output "Number 10" because we specify that $i must be less than 10, not less than or equal to it. Here is the output:

Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9

The \n part at the end of the string is what causes the new lines, so if you're using Windows you'll need to use \r\n. This is all explained later - don't worry about it too much for now. The third loop type takes the form do...while, and is similar to a while loop with the difference that it is always executed at least once. Consider the following piece of code:

<?php
    $foo
= 12;
    while (
$foo < 10) {
        
do_bar();
    }
?>

In that situation, the do_bar() function will never be called, because $foo will not be less than 10. However, in a do...while loop, we have this:

<?php
    $foo
= 12;
    do {
        
do_bar();
    } while (
$foo < 10);
?>

In the latter case, do_bar() will be executed before $foo is compared against 10. If $foo is less than 10 when checked, the loop executes again. As you can see, the only difference between a while loop and a do...while loop is that the latter is always executed a minimum of once.

The last type of loop is the foreach loop, and is used to loop through an array of data. As arrays are quite unique in how they work, this particular type of loop is covered specifically in the Arrays chapter.





<< 2.6.9 Case switching   2.6.11 Infinite loops >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
valsj@yahoo.com - 30 Aug 2008

ive been looking for the pdf file of this but i cant find one. anybody got it first? please send me an email.thanks

Th3_Designer. - 30 Aug 2008

Dude,

You're a Gee neee Ussss

raremunchen@yahoo.com - 30 Aug 2008

Please send me the zip file or Pdf file thanks

A Concerned Commenter - 30 Aug 2008

People,
There are two ways to use PHP.

1. With apache.

2. On the command line.

I don't know all the ins and outs of PHP, but you should have read this earlier. The author makes it clear. The author is working with the command line (#2).

To get a new line, depends on your method of using PHP.

1. (Apache) <br>

2. (command line) /n

Please read the book a few times before saying you don't understand, or can't follow. It may take a little more effort, but you will learn how to deal with the world in a better way. Thanks, and good luck to all you Coders, and thank you to the author who is presenting good information.

InvalidSyntax - 30 Aug 2008

This is the best tutorial ever its verry good writing..
Im kinda stuck on why use $i = 1
alot of poeple use that in tuts loops are alittle wierd but im sure ill grasp em one day lol

Keep up with your awsome writing skills...

-mark

Thomas - 30 Aug 2008

I'm using Windows Xp SP2. The manual said to do the following:

The \n part at the end of the string is what causes the new lines, so if you're using Windows you'll need to use \r\n.

But \r\n still does not work for me, I still have to use <br />. Anyway this tutorial is awesome :)

Randolph - 30 Aug 2008

To the guy above in doubt about the difference between
$myVar = "variable"; and
$myVar = 'variable';

in this particular case, really, there is no difference using "" or ''. But try to do:

<?php
$otherVar = "other variable";
$myVar = "variable and $otherVar";
print $myVar;

$myVar = 'variable and $otherVar';
print $myVar;
?>

I hope you`ll get the point with this simple example :)

Raul - 30 Aug 2008

This loop is excelent.

I still have the problem that when I use \n there is not a new line, is moving to the rihgt all the time.

This tutorial is GREAT.

Raul
www.auctionlinux.com
www.impelse.com (Linux Store)

Raul - 30 Aug 2008

This loop is excelent.

I still have the problem that when I use \n there is not a new line, is moving to the rihgt all the time.

This tutorial is GREAT.

Raul
www.auctionlinux.com
www.impelse.com (Linux Store)

Raul - 30 Aug 2008

This loop is excelent.

I still have the problem that when I use \n there is not a new line, is moving to the rihgt all the time.

This tutorial is GREAT.

Raul
www.auctionlinux.com
www.impelse.com (Linux Store)

A PHP User - 30 Aug 2008

i forgot to mention i'm using linuz ;)

A PHP User - 30 Aug 2008

the /n in the script doesn't work on my server, i had to replace it with <br> in order for it to make lione breaks...

Matthew Bonner - 30 Aug 2008

while (1) {
//actions
}

is a faster infinite loop than

for (;;) {
//actions
}

although the difference is only marginal.

Matt - 30 Aug 2008

For the sake of comparison, these two scripts work the same.

<?php
for ($i = 1; $i < 10; $i = $i + 1) {
print "Number $i <br />\n";
}
?>

and

<?php
$i = 1;
while ($i < 10) {
print "Number $i <br />\n";
$i = $i + 1;
}
?>

This just shows how for and while are different.

A PHP Newbie - 30 Aug 2008

Code:
<?php
for ($i = 1; $i < 10; $i = $i + 1) {
print "Number $i\n";
}
?>

Executing that within a web browser will simply add a new line to the *source*, not the page itself. This was covered earlier. If you do the following:

<?php
for ($i = 1; $i < 10; $i++) {
print "Number $i<br />\n";
}
?>

It will output

Number 1<br />
Number 2<br />
Number 3<br />
Number 4<br />
Number 5<br />
Number 6<br />
Number 7<br />
Number 8<br />
Number 9<br />

In the source code, which would create the line breaks in the web page as well as the source.

A PHP User - 30 Aug 2008

I tried this.

<?php
for ($i = 1; $i < 10; $i = $i + 1) {
print "Number $i\n";
}
?>

but I dont get the lines on the next line, they all extend to the right.

Tried using \r\n too, but still the same.

My server is Unix btw.

A PHP User - 30 Aug 2008

The difference between

$myVar= "content";

and

$myVar= 'content';

is: the content in the double quotes will be interpolated ( see http://www.hudzilla.org/phpbook/read.php/2_6_0 ), the content in the single quotes will NOT be interpolated by the php-interpreter and is so faster.

Dirk

Another Problem - 30 Aug 2008

In a variable, for example:

$myVar = "variable";

and

$myVar = 'variable';

seem to be the same when executed

I really want to know if there are any differences between them.

Problem - 30 Aug 2008

I've always had problem with cases of loops. No matter in PHP, JavaScript or ActionScript (especially this one, which has been hurting me for months)

Any suggestion to make loops clear enough? However, through your tutorial, I've understood like 75% already (personal measurement:)

LEo! - 30 Aug 2008

good job man, keep it up. i'm totally in this amazing world now:)



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is five plus zero?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow