Loops In PHP

Hi guys,

I have been receiving very good feedback from different users from different countries and I am loving it.

I have replied to all of those students who have sent me their assignments and have asked any questions though I will request you to ask questions in the comments of a specific articles so that other readers can also get knowledge about the points you ask me.

Let’s move towards our today’s lecture which is about Loops.

There are certain conditions in which you need to execute the same block of code again and again. For example if you want to print ten consective equal signs in three lines to make a separater then you could do it with different methods. One could be to use three echo statements and put ten equal signs in each i.e

  echo "==========" . "<br>";
   echo "==========" . "<br>";
echo "==========" . "<br>";

Apparently it’s not that hard to do so with echo statement but imagine if you have to print 100 such lines that means you will write 3 x 100 = 300 echo statements. Loads of typing and hassles to organize them. Here we can use Loops to write few lines which will print more output depending on our loops condition.

Before we get to the actual loops explanation lets understand the basic working of loops.


Basic Concept Of Loops:

We use braces {} to make block of code that we want to execute for a specific number of times. This is called the body of loop. Every loop depends on a condition. It keeps executing the block of code unless the condition is met true or stand false (depends on the loop’s type that we will discuss in a moment).

There is a terminating point for each loop that ends the loop when the condition is satisfied. Like in our earlier discussed example if we want to display hundred lines of ten equal signs each then we have the following attributes that will make up our loop in theory;

1) Condition: hundred lines: keep printing unless hundred lines are printed.

2) Body of the loop: in which we will put the printing stuff that is echo stamtement to print equal signs plus some additional contents that will help our loop to execute for the desired number of timing (will discuss in a moment)

3) Terminating Point: when hundred lines are printed the loop must turminate

4) Loop Run:

Every time the block of code (body of loop) executes the loop completes its one RUN.

Isn’t it easy? Yeah it is and it will be more easy for you once we discuss the actual loops. So let’s do it!

Remember, I am using these terms from my own dictionary because I will use them to explain things otherwise these terms or not standard and attached with loops definitions you can use whatever theory you want to explain these terms in your own words.


Types Of Loops:

PHP offeres four types of loops

  1. FOR Loop
  2. While Loop
  3. Do-While Loop
  4. Foreach Loop

Now we will discuss them one by one.


For Loop:

Basic Syntax of For Loop is as follows,


FOR Syntax:

for(initialization; condition; increment / decrement) {
//body of loop
// increment / decrement

Here ‘for’ is the keyword following by parens that contains three attributes

Initilization: the initial value of the loop from where the loop will pick the starting value

Condition: the condition that the loop will check after each loop run and will decide whether it has to execute another loop run or terminate

Increment / Decrement: this portion will either increment or decrement the initial value to continue.

Let’s write the first programme that will use FOR loop to print equal sign (=) ten times in each row for hundred lines

for($i=1; $i<=100; $i++) {
   echo "==========" . "<br>";

Now let’s analyze the above code.

First the control picks the loop initial value as 1 and compare it with the condition which says that $i value can be less or equal to 100 which stands true because $i current value is 1 so the loop completes its first run in which it displays one line of equal signs and increment $i value by 1. On reaching the closing braces the control again goes back to the Condition and compare $i value which is 2 now. The condition again stands true as 2 is less than 100 and loop completes another run. Similalry it performs the same operation unless the $i value comes 100.

When $i is 100 then the condition stands true and loop completes its hundredth run and increment $i to 101. Now on comparison the condition stands false because 101 is not equal to 100 nor less than it so the loop reaches termination point and the control is sent out of loop body.

Let’s learn a new term.

Loop Variable: The variable involved in loop initialization, condition and increment is knows as Loop Variable. So what’s our loop variable in the above example? yeah, it is $i.

Let’s perform the same operation with FOR loop but with a different method.

for($i=100; $i>=1; $i--) {
   echo "==========" . "<br>";

Now our intial value of loop variable is 100. So you will be thinking that how we are going to print the line for hundred times? We will do so because we also changed the Condition that is now comparing $i unless it is greater or equal to 1. And the third attribute is now decrement and not increment so the loop variable will start from 100 and will decrease its value by 1 for each loop run i.e 99,98,97 ……. , 1 and when it will reach 0 the condition will stand false and the loop will terminate.

Let me clear one more thing, in most of the books, articles and tutorials of PHP loops you will mostly see i, j or k etc as loop variable. Please do not attach them with loops as standard, it’s just a simple variable and its name could be anything. I have noticed sometimes students misinterpret this and think that it’s must to use these alphabets as loop variables names which is totally wrong. Like a person criticised me in one of my previous articles that why didn’t I use “Hello World” as the first programme of PHP.

Anyway, you should remember one more thing that it is not necessary to increase or decrease loop variable by 1 each time. You can use any increment or decrement value you like. For example I can display 50 lines from the same above code just by decreasing the loop variable by 2 in each run i.e

for($i=100; $i>=1; $i-=2) {
   echo "==========" . "<br>";

You can also decrease the value by 2 like $i=$i-2. Here you must notice yet another thing that increment or decrement part of the loop doesn’t use semi-colon.

There could be different styles to write the FOR loop code e.g

for($i=100; $i>=1;) {
   echo "==========" . "<br>";

The above code also works though we have brought the decrement part to the main body of the loop.

Mug my words and mug them well; You should learn improvisation to be the best programmer. So keep trying different things yourself to spread the circle of your imaginations to be a good programmer who can perform different tasks with different logics.

Try this and email me what output you get from the following code:

for( ; ; ) {
   echo "==========" . "<br>";

Now we will go through the WHILE and Do-While loops quickly because the basic concept is same.



FOR loop is a definite loop because you know the number of loop runs before the loop starts. However WHILE loop is indefinite loop because it works on mainly a condition that can stand true for unknown number of loop runs.

Let’s explain it with a broader example. Suppose you have 1000 students names and you want the loop to read each name and perform some action unless the name appears as ROB.

the rough psuedo code could be,

while(name != ROB) {
// While body

that means unless name variable is matched to be ROB the loop should carry on.

Now let’s stick with our equal signs example to perform the same operation with WHILE LOOP.

  while($i <= 200) {
   echo "========== \n";

Same initialization, Same condition that is checked everytime the code is ready to run, same increment / decrement portion, same use of braces to make the loop’s body. Just a different method and syntax.

Indefinite loops are also called iterative loops because real time indexing is not constant. For a very good understanding of definite and indefinite / iterative loops you can study http://www.cs.duke.edu/~ola/patterns/plopd/loops.html#definite-process-all-items.

What if I write something like


while($i<1) {
  echo "how many loop runs this will have?";

Hmm, if you have understood the basic theory of the loops then you must know that loop will not run even for a single time because for the very first condition check the condition stands false and the control will go outside the loop body right a way.

What if I want to run the loop atleast once regardless of condition true or false status?

In such situation we can use do-while loop.


Do-While Loop:

Do-While loop will run the loop atleast once before it checks the loop condition and hence it’s handy in the situation where we need to run the loop for the first time without checking the condition.

the basic structure of do-while loops is as follow,

do {
//block of code that will be executed in each loop run

How many times my name will be printed from the following code?

do {
  echo "Haroon";  

The first time control reaches the while condition the $i value is 3 and it stands false and the loop is ended however you already printed my name once because do-block of code executed already before reaching the condition.

do-block of code is made using keyword ‘do’ and pair of braces.

So by now you have learnt three loops types in php out of four.

The basic concept of the functionality of all loops is same that contains initialization, condition check and increment / decrement , termination of loop, body of loop etc etc. Though the syntax and process flow are different.

The fourth type of the loop in php is FOREACH loop which is used with Arrays. Have we studied Arrays? Yeah, I know we haven’t yet, so lets skip this loop for now and we will cover it in our next lecture that will be on Arrays.

I love assignments so please be my favorite by completing your assignments regularly.



Make a form that has one field where user can submit a digit and on the receiving page display its table.

FOR and WHILE loops could be of same basic functionality though I want you to show my your skills to improvise with do-while loop and did you forget what I said about improvisation earlier?

Till you read me again, take care of yourself and keep practicing and make a habit to improvise your code and ideas to be a programmer who can rapidly think off logics to solve problems.

- Haroon Ahmad


Related Articles:

FAST PHP Tutorial (Part 1)
How to Install PHP on Windows (Fast PHP Tutorial Part 2)
How To Install PHP On Linux
How To Install Apache on Windows
Easy Installers to Install PHP, MySQL, Apache on Windows
PHP Programming Basics
Operators in PHP
Decision Making using IF-ELSE in php
Decision Making using PHP Switch Statement

Share this page:

0 Comment(s)

Add comment