If you like this post then please subscribe to my full feed RSS. You can also subscribe by Email. Not sure how this works?

The ability to perform repetitive tasks is a very important aspect of any programming language. Imagine an array with 500 elements. You wouldn't want to write 500 statements to read 500 elements. Instead, you can write a single loop statement that will perform an action to all 500 elements. A loop will continue to operate until a condition is achieved, or you choose to exit the loop. According to our 500 example, you can create a loop structure that will continue to read elements from an array until it has reached the last element (500).

You can define a simple loop structure in PHP using the "while" statement, which at first may look similar to the "if" statement:

while(expression)

(statements)

As long as the expression evaluates to true, the statements are executed over and over again. You wouldn't want your loop to go on forever, so you should change something within the block of statements that will affect the expression. For example:

$counter = 1; //this is out counter variable

while($counter < 10) //keep running the following statements as long as "$counter" holds a value that is smaller than 10

{

print $counter; //output the "$counter" value

$counter++; //increment "$counter"

}

This will output "123456789". The counter variable will start from 1; its value will be outputted, then the variable will be incremented by 1. The loop continues as long as the variable's value is smaller than 10; once it reaches 10, the loop structure will stop, so "10" will not be outputted.

The "do…while" statement is similar to the "while" statement. The only difference between the two is that when using the "do…while" statement the block of statements is executed before the truth test and not after it. This way the block of statements will be executed at least once, even if the expression evaluates to "FALSE":

do

(statements)

while(expression);

A much neater and safer way to implement a loop structure is using the "for" statement. This isn't much different from a while statement, in fact there is nothing you cannot achieve when using for statement that you cannot do with a while statement. It only requires you to write a smaller amount of code:

for(variable assignment; test expression; variable increment)

(statements)

Whereas in order to properly use a "while" statement you must initialize a variable outside the statement, then increment it and test it, all of these in different parts of the structure, using "for" you can do that using a single statement. This makes your code more compact and also makes it less likely that you will forget to increment a counter variable, thus creating an infinite loop. So here is how we can rewrite the previous counter example:

for($counter = 1; $counter < 10; $counter++)

{

print $counter;

}

Well, this looks a lot better. It's more compact, and you can see how the loop variable will perform at a glance. You probably have figured out on your own that this will output "123456789".

While all of this looks very fine, there are times when you need more control over a loop. PHP includes two useful functions for this: "break" and "continue". "break" does exactly what its name says: it just breaks out of the loop. This way you can take care of any unexpected actions that the loop might stumble upon. Let's say you have to sum up a list of prices. If someone has added a negative price to the list by mistake, this could really make a mess out of your calculations. On the other hand, you can use "continue" is used to skip the current iteration, but don't end the loop. "continue" just passes on to the next iteration, without running the following statements in the group. In our price list example, this could come in handy when you want to skip certain prices, so you can create a sub-total.

for($num = 0; $num < 20; $num++)

{

if($prices[$num] < 0) //if we encounter a negative price…

{

print "Error: You have negative prices!";
//output an error message

break; //exit the loop!

}

if($prices[$num] > 1000) //if we encounter prices higher than $1000, we apply a discount

continue; //don't continue to the next statement that will add them to the total sum, we have to perform discount calculations

$total += prices[$num];

}

PHP also implements a loop structure that works only on arrays, called "foreach". It will return an error when you try to use it on a variable with a different data type or an uninitialized variable.

foreach(array_expression as $value) statement

foreach(array_expression as $key => $value) statement

The first syntax is used to loop over an array, while assigning the value of the current element of the array to $value. PHP keeps count of the current index, so you don't have to worry about that, it will continue to assign elements starting from the first one until the last one, with no exceptions. The second syntax does the same thing, except that the current element key will be assigned to the variable "$key" on each loop. It's good to know that "foreach" operates on a copy of the array, not the array itself. Returning to our previous script, we can rewrite the code like this:

foreach($prices as $num) //assigns the value of each element in the "$prices" array to "$num", then does the following…

{

if($num < 0)

{

print "Error: You have negative prices!";

break;

}

if($num > 1000)

continue;

$total += $num;

}

While it may look confusing at first, just keep in mind that "$num" now holds the actual value of the array's element, not its index in the array.

Did You Enjoy This Page? These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • MisterWong
  • BlinkList
  • Furl
  • Netscape
  • Spurl
  • StumbleUpon
If you like this post then please subscribe to my full feed RSS. You can also subscribe by Email. Not sure how this works?

One Response to “PHP Loop Structures”

  1. Nice explanation on how different loops work.thanks alot for the wonderful work

    valence

Leave a Reply