My Linux and Open Source Software Penguin Logo Linux and Open Source News and Reviews
The Hungry Penguin
Linux & Me Blog    My Linux Blog (Archived)    What is Linux?    What is Open Source?

Sidebar

Open Source and the London Olympics



Dedicated Servers

Looping in PHP

Introduction

When you loop a piece of string you make a curved shape which bends until one part of it crosses another part of it. You make a circle which goes back to the its beginning. When an aircraft does a loop it follows the form of a loop in the sky and returns to its starting point. Computer loops aren't very different. To repeat a sequence of events many times a computers loops back to the beginning and does them again. In this tutorial we will look at how to loop in PHP.

Prerequistes

Level: beginner

To follow this study you need to know at least how to create and run a PHP script and have some understanding of PHP variables.

While

The while loop is the simplest type of loop in PHP. It gets its name from the natural usage in English. While it rained we wore our hats. While something was true an action was performed. When it stopped raining the hats came off! In PHP it is the same:

	while (an expression is true) {
	do something
}

So if you wanted to print the numbers 1 to 10 you would write:

$i=1;				// Set the initial value of loop to 1
while ($i <= 10) {	// Loop while $i is less than or equal to 10
	print $i.”<BR>”;	// Output $i followed by a HTML break tag
	$i++;			// Increase the value of $i by 1
}				// End of the loop

This above code will print the numbers 1 to 10 on separate lines (thanks to the <BR> tag). Each journey around the loop is called an iteration. If we wanted the numbers 99 to 88 then you would write:

$i=99;			// Set the initial value of loop to 99
while ($i >= 88) {	// Loop while $i is greater than or equal to 88
	print $i.”<BR>”;	// Output $i followed by a HTML break tag
	$i--;			// Decrease the value of $i by 1
}				// End of the loop



In real world applications the while loop would be used to loop through data until the end. This could be data in an array, from a database or from a file.

One other thing to note about the while loop is that it can make 0 iterations, if the condition is false before the start of the loop. For example if $i was set to 55 and the the condition was >= 88:

$i=55;			// Set the initial value of loop to 55
while ($i >= 88) {	// Loop while $i is greater than or equal to 88

Then the loop would not iterate at all and the code in the loop would never be run as 55 is never going to be greater than or equals to 88.



Do..while

The next loop in PHP is the do..while loop. Do something while a condition is true. A do..while loop is loop is very similar to a while loop with one important difference, the truth expression is checked at the end of each iteration and not at the beginning. This means that a do..while loop is guaranteed to run at least once. First here is the numbers 1 to 10 in a do..while loop:

$i=1;				// Set the initial value of loop to 1
do {				// Loop
	print $i.”<BR>”;	// Output $i followed by a HTML break tag
	$i++;			// Increase the value of $i by 1
} while ($i <= 10);	// Loop while $i is less than or equal to 10

Note the semicolon at the end of the while, this is different than the normal while loop. As the loop is guaranteed to run at least once, lets set $i to 20 and see what happens:

$i=20;			// Set the initial value of loop to 20
do {				// Loop
	print $i.”<BR>”;	// Output $i followed by a HTML break tag
	$i++;			// Increase the value of $i by 1
} while ($i <= 10);	// Loop while $i is less than or equal to 10

If you run the above code you will see that you get the number 20 displayed. This is because the loop runs at least once even though 20 is clearly not less than or equal to 10!

For

PHP has a more complex type of loop called the for loop. A for loop is really a while loop in disguise. Going back to a normal while loop we notice three distinct steps in running the loop. First the variable initialization, second the increase (or decrease) of the loop variable and last the condition. For example:

$i=1;				// INITIALIZATION
while ($i <= 10) {	// CONDITION
	print $i.”<BR>”;
	$i++;			// CHANGE THE LOOP VARIABLE
}

A for loop puts these three stages into a more compact form, for(initialization; condition; loop variable). The initialization is executed once, unconditionally, at the beginning of the loop. At the beginning of each iteration, the condition is evaluated. If it is true, the loop continues. If it is false the loop ends. At the end of each iteration, the loop variable expression is run. So here is the numbers 1 to 10 again:

	
	for($i=1; $i<=10; $i++) { // Start at 1, loop while <= 10, incrementing by 1
		print $i.”<BR>”;	// Output $i followed by a HTML break tag
	}
	

It is possible to leave out any of the three expressions. If some earlier code performed some calculations and the loop was based on that calculation, we might not want to include the initialization:

	// $i is set earlier
	for(; $i<=10; $i++) { 	// Start at 1, loop while <= 10, incrementing by 1
		print $i.”<BR>”;	// Output $i followed by a HTML break tag
	}

Note that the semicolon remains. If all three expressions are empty then the result is an infinite loop:

	for(;;) {
		print “Infinite...<BR>”;
	}

Break

The break command breaks out of the current loop and is very useful for terminating a loop in the middle of execution. First a simple example, here is a 1 to 10 again this time using a break:

	for($i=1;; $i++) { 	// Start at 1, incrementing by 1
		print $i.”<BR>”;	// Output $i followed by a HTML break tag
		if($i>=10) break; // If $i is >= to 10 then break out
	}

Note that the middle expression, the condition, is empty. Normally such a for loop would run forever as there is no condition to halt the loop. However the condition is now found in the if statement. If $i is greater than or equal to 10 then break out. The break can also be used in the simple infinite loop:

$i = 1;				// Initialization
for (;;) {				// Infinite loop
    print $i.”<BR>”;		// Output $i
    if ($i >= 10) break;	// If $i is >= to 10 then break out
    $i++;				// Increment $i
}

Of course this is now starting to look like a while loop and it could be written like this:

$i = 1;
while(true) {
    print $i.”<BR>”;
    if ($i >= 10) {
        break;
    }
    $i++;
}

Here the while(true) is an infinite loop much like the for(;;).

Say we need to have an odd random number between 1 and 30. One way to get one is using a for loop and the break statement. However before showing you the next example, it must be pointed out that this is a very inefficient way to get such a random number, however it does show nicely the use of the break command:

	for(;;) {
		$i=rand(1,30);
		if($i % 2 != 0) {
			print “OK: $i<BR>”;
			break;
		}
		else
		{	
			print “NO: $i<BR>”;
		}
	}

PHP has a random number function called rand(). It takes two optional parameters min and max. The % in $i % 2 means modulus which calculates the remainder of $i divided by 2. An even number will always have a remainder of 0 when divided by 2 and an odd won't! The output of such a loop could be something like this:

NO: 14
NO: 2
NO: 16
OK: 3

The first three times around the loop resulted in three even numbers 14, 2 and 16. These caused the second part of our if statement to run rejecting the number as even and displaying NO. The forth time around 3 was generated which is odd. Here the first part of the if statement is run. OK is output and then the break statement stops the loop and end the script.

Final words

When writing PHP scripts, looping can be a very powerful tool. Always remember to choose the correct loop for the job. Choosing the wrong loop could land you into more trouble. From personal experience the for loop is generally the most used as really it covers all the aspects of the while loop but yet in a more compact form.

Enjoy!

Author's bio

Gary Sims has a degree in Business Information Systems from a British university. He worked for 10 years as a software engineer and is now a freelance Linux consultant and writer. You can contact him via his website http://www.hungrypenguin.net


Linux News | Linux Articles | Linux Distributions | Linux Apps | Linux Kernel | Free Linux Download | Linux & Me Blog
Free Press Release Service | Bible Study Tool | New Covenant Workshop | Gary Sims
Press Releases and SEO

The original content of these pages (not the syndicated items) is licensed under a Creative Commons License.
News and media about the Linux operating system, open source software, Unix, Apache, LAMP, PHP, RSS, GNU and much more.