Articles in Basics Category

PHP Loops

Loops let you execute a block of code number of times. Loops often come into play when you work with arrays. Rather than writing same piece of code for each array element, it’s preferred to use a loop where the particular code block is written only once.

While Loop

While loop runs till the given condition is true. In following example, we print numbers from 1 to 5 (<br /> tag is used to have line breaks in web browsers).

$i = 1;

while ($i < 6) {

	echo "Number $i <br />";


Note that there should be something inside the loop that makes the condition false ultimately. Otherwise it will run endlessly. In above example, we increment value of $i by 1 in each iteration so ultimately it will be 6 which stops the execution of the loop.

Following example deals with an array. Think that you are programming a game that has several stages and store score of each stage in an array.

$stages = array(50, 110, 130);
$count = count($stages);
$i = 0;

While ($i < $count) {

	echo "Stage $i Score: ".$stages[$i].'<br />';


Above code segment would print following lines in your web browser.

Stage 0 Score: 50
Stage 1 Score: 110
Stage 2 Score: 130

We store number of elements in the array in $count. Even though the array is defined here, in the real program, it would be dynamically assigned and you may not know number of stages a particular player has played. $count saves us from that trouble.

We start our incrementer ($i) at 0 since Indexed arrays start from key 0. Here keys are 0, 1 and 2. And the count of array elements is 3. So, the condition ($i < $count) will be true till the end of array (means till element $stages[2]) and will be false when $i becomes 3 which happens after the execution of element $stages[2];

If your stages begin from 1 then you can simply change the echo statement as below.

echo 'Stage '.($i+1).' Score: '.$stages[$i].'<br />';

Do While Loop

Do While loop is similar to While loop. Main difference is that the condition comes after the loop body so that the loop runs at least once.

do {

	echo "Stage $i Score: ".$stages[$i].'<br />';

} while ($i < $count);

While vs Do While

In practice, you would often find While loop in use instead of Do While. The reason is While loop seems to be straight forward and simple to understand. And also almost all the implementations you do with Do While can be implemented with While. Provided that, following differences can be identified.

  • Do While loop runs at least once even when the condition is false.
  • Do While executes the condition one time less than While.

For instance, in above examples, While executes following four conditions.

(0 < 3)
(1 < 3)
(2 < 3)
(3 < 3)

And Do While executes only three conditions since 0 element is already printed before the condition.

(1 < 3)
(2 < 3)
(3 < 3)

So, if your condition is too complex (say contains several ANDs and ORs) then using Do While would save you bit of time.

However when you use Do While be careful that variables and other elements inside the loop body are properly set. For an example, if $stages array was empty, above Do While example would throw an Undefined offset: 0 error since there is no element defined as $stage[0].

But in While example, it won’t happen since the condition becomes false (0 < 0) and loop body won’t be executed at least once.

Performance often depends on hardware (which is improved day by day) and saving microseconds may not be worth if your code is difficult to understand or makes room to errors.

For Loop

In While loops, you have to define the incrementer outside the loop and then increment it inside the loop in a separate statement. For loops address these facts inside the loop start. Our Stage Scores example can be implemented using a For loop as below.

$stages = array(50, 110, 130);
$count = count($stages);

for ($i=0; $i<$count; $i++) {
	echo "Stage $i Score: ".$stages[$i].'<br />';

You can see three statements at the start of For loop. First one is the definition of the incrementer. Second one is the condition and third one is for incrementing the incrementer.

Note that many times you would see that array count is implemented in following way instead of above way. That is calling count() function inside the condition.

for ($i=0; $i<count($stages); $i++) {

This method is ok if the array contains only few items as in this case. But think that array contained hundreds or thousands of elements. Then for each iteration count() function will be executed which is unnecessary and which can consume bit of processing time.

For loops come handy when dealing with multi-dimensional arrays. Think that you want to display scores for more than one player. You can achieve that as below.

Note how $i and $j incrementers are used. These types of implementations are called Nested For Loops. In these, inside each iteration of first For loop, an entire second For loop runs.

$players[0] = array(50, 110, 130);
$players[1] = array(50, 145, 170);
$players[2] = array(50, 90, 205);

$count1 = count($players);

for ($i=0; $i<$count1; $i++) {

	$count2 = count($players[$i]);
	echo 'Player ' . ($i+1) . ' Scores: ';

	for ($j=0; $j<$count2; $j++) {

		echo $players[$i][$j] . ', ';


	echo '<br />';


After running, above code segment will print following lines in your web browser.

Player 1 Scores: 50, 110, 130,
Player 2 Scores: 50, 145, 170,
Player 3 Scores: 50, 90, 205,

Foreach Loop

Foreach loop acts only on arrays and acts similar to For loop. Difference is you don’t have to define an incrementer and increment it. There is also no condition to evaluate. It would run for each item in the array and won’t run at all if the array is empty.

$stages = array(50, 110, 130);

foreach ($stages as $value) {
	echo $value.'<br />';

Above code segment will print following lines in your web browser.


Since there was no accompanying incrementer in the loop, we couldn’t print stage numbers. However we can define an incrementer outside the loop and increment it inside the loop to keep track of number of iterations it runs.

We had the same approach in While loops but there the incrementer was actually used in the condition of the loop. Here there is no involvement of the incrementer to the execution of the loop.

$stages = array(50, 110, 130);
$i = 0;

foreach ($stages as $value) {

	echo "Stage $i Score: $value <br />";


Note that in each iteration the value of corresponding array element is assigned to the variable $value. Then we can use it inside the loop body. You can use any variable name here.

We can use Foreach loops on Associative arrays as below.

$stageAssoc = array('Stage 0'=>50, 'Stage 1'=>110, 'Stage 2'=>130);

foreach ($stageAssoc as $key=>$value) {

	echo "$key Score: $value <br />";


Foreach loops can also be used on multi-dimensional arrays.

$playerAssoc['Player 1'] = array(50, 110, 130);
$playerAssoc['Player 2'] = array(50, 145, 170);
$playerAssoc['Player 3'] = array(50, 90, 205);

foreach ($playerAssoc as $key1=>$value1) {

	echo $key1.' Scores: ';

	foreach ($value1 as $value2) {

		echo $value2.', ';


	echo '<br />';

For vs Foreach

According to above examples, you can see that Foreach loops are more simple and appropriate for Associative arrays and when you don’t have to keep track of iterations. For Indexed arrays, For loops are more appropriate since their incrementers are nicely associated with the keys of Indexed arrays.

Where to Head from Here...
Share with Your Peers...

We Value Your Feedback...

We love to hear what you think about this article. Please provide your opinion, suggestions and improvements using following form. Note that submitted feedback is not displayed but we will get back to you if it needs a reply.