Looping Statements and Arrays in PHP – Part VII

Till now, we have learned quite a bit of PHP and are capable of writing some decent applications too. Now in this part of the course, we will learn about two very important things in almost any programming language – loops and arrays.

Firstly, you might be thinking what “loops” are and why do we need to learn it? Looping is nothing but a way to save yourself from the tedious job of doing many repetitive tasks. Quite often we need to perform a particular action (or a set of actions) repeatedly for a large no. of times and it is sometimes absolutely impossible to do that manually. Looping is just the way to automate the job of performing a task repeatedly for any no. of times with ease.

In PHP, there are four types of looping statements and in this part of the course we will learn in-depth about all of them. There may be four different types of loops but the idea and their working nature is very similar. So the four looping statements available in PHP are –

i) The while Loop

ii) The do-while Loop

iii) The for Loop

iv) The foreach Loop

Let us start with the most basic looping statement first – the while loop.

The while Loop

The syntax of the while loop is something like this,

 while (condition){

// set of actions to be performed

}

The syntax essentially means that “while a condition (or a combination of conditions) is true, then a particular action (or a set of actions) will be performed and will be stopped as soon as the condition turns out to be false.

It is a very simple and easy to understand looping statement and I hope you have already grabbed the idea behind its working. But let me make it even more clear to you with an illustrative example.

Now suppose you have participated on a 100m race event and want to track your progress from the start to the end. So let us write a PHP script for that using a while loop.

[php]<?php

$distanceCovered = 0;

while($distanceCovered <= 100){

if($distanceCovered == 0)

echo ‘Race started…</br>’;

else if($distanceCovered == 100)

echo ‘Race finished.</br>’;

else

echo "Distance covered – $distanceCovered </br>";

$distanceCovered++;

}

?> [/php]

Here, we are using a counter variable named “$distanceCovered” which is initially set to zero (as the race haven’t started yet). In the while loop we have given the condition ($distanceCovered <= 100) and we are displaying the progress after every meter covered.

The do-while Loop

The do while loop is very similar to the while loop with just a single bit of difference. The while loop may not execute the body (of the loop) even once if the condition is false from the beginning, but the do-while loop will execute at least once even if the condition is false right from the beginning.

The syntax of the do-while loop is something like this,

 do {

// set of actions to be performed

} while (condition);

The syntax clearly depicts that the condition is not checked at the point of entry and the body of the loop will be executed at least once and then the condition will be checked and the body will be repeated further depending on the condition’s truth or falsity.

For example,

[php]<?php

do{

echo ‘I will be shown at least ONCE.</br>’;

}while(0);

?> [/php]

Here, I have put “0” (or false) in the loop condition which means that the loop shouldn’t be executed even once if it was a simple while loop. But the do-while loop is different from the while loop, just at this point where the condition checking is not performed at the entry point. So, the body of the loop gets executed once and we get the following output.

do-while-loop

You can also put “1” (or true) in the condition and check the output yourself. You will be getting an abnormal output in this case and the page will crash as the condition is true for all the time and loop runs for an infinite no. of times.

The for Loop

The syntax for the “for” loop is a bit different from the while or the do-while loop. Some newbies claim that the for loop syntax to be difficult to understand but it is absolutely not. It is just a bit different from the other ones, that’s it.

The syntax of the for loop is something like this–

 for (initialization; test-condition; increment/decrement){

//the set of actions to be performed

}

To understand the working of the “for” loop fully, we need to understand the flow of control of the loop.

  • First, the initialization statement will be executed which will set the counter to its initialization value. This statement will be performed once and only once.
  • Next the flow would move to the test condition statement and will check if the condition is true or false.
  • Depending on the condition the body of the loop would be executed and the flow will move downwards. If the condition is true, the flow will enter the body of the loop and execute the entire body, and if not then the loop will be terminated.
  • After the body of the loop is executed, the flow would move up to the increment/decrement statement to change the counter variable accordingly.
  • Next the flow would again move to the test condition and the cycle would continue.

Let us try a simple example using a for loop,

[php] <?php

for($counter=0; $counter<=10; $counter++){

echo ‘Counting ‘.$counter.'</br>’;

}

?> [/php]

You should also try and rewrite the first script that we wrote – the 100m race event script using a “for” loop. It is left as an exercise for you to try and improve your understanding further with loops.

Arrays in PHP

To understand the next looping structure we need to learn a bit about arrays in PHP. We will just try to grab a basic idea and understanding about arrays so that we can move ahead in understanding our special looping statement.

array-illustration

Array is a data structure that stores a collection of similar type of values in a single variable. The usefulness of an array is tremendous. Suppose, you want to store the names of all the students in your class and there are 100 such students. Then from your current knowledge in PHP, you would do something like this,

[php] <?php

$name1 = “John”;

$name2 = “Drake”;

$name3 = “Tim”;

……

$name100 = “Jack”;

?> [/php]

But it is never an intelligent approach to declare 100 variables to store the information. Now this is the point where the concept of array comes into play which allows us to group all the data in a single variable and access each data items using an ID known as the “array index”.

There are three types of arrays in PHP –

i)    Numeric Arrays – Here the elements of the array are accessed with a numeric value starting from 0.

ii)    Associative Arrays – Here the elements of the array are associated with key values which are strings rather than numeric values.

iii)    Multi-dimensional Arrays – Here we have one or more arrays within another array and are accessed using multiple indices.

We will discuss in detail about each of them with lots of examples in the next part of the course. But right now let us learn how we can create an array in PHP. There is a very simple method to create an array which is discussed as follows,

[php] <?php

$name[0] = "John";

$name[1] = "Drake";

$name[2] = "Mary";

$name[3] = "Tim";

$name[4] = "Jack";

?>

&nbsp;

Or we can make use of an <b>in-built function array()</b> to create an array in a simple and effective way,

&nbsp;

[php] <?php

$name = array("John", "Drake", "Mary", "Tim", "Jack");

?> [/php]

Now let us move on to learning the special looping statement – foreach loop.

The foreach Loop

Now if we need to access the elements of the array individually we can make use of any of the loops which we have discussed previously like the while, do-while or the for loop. There is absolutely no problem with it. For example,

[php]<?php

$name = array("John", "Drake", "Mary", "Tim", "Jack");

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

echo "$name[$i].</br>";

}

?>[/php]

array

But there is a more efficient way to loop through arrays using a special looping statement known as foreach looping statement.

The syntax is something like this,

foreach (array as value){

//actions to be performed

}

The syntax simply means that “for each individual element of the array, perform a particular set of actions corresponding to that element.”

For example,

[php]<?php

$name = array("John", "Drake", "Mary", "Tim", "Jack");

foreach($name as $value){

echo "$value </br>";

}

?>[/php]

Here, for each iteration an individual element from the array ($name) is assigned to the $value variable and the body of the loop is executed for each iteration. It is a very simple, time-saving and efficient way to loop through arrays.

The Last Words

In this part of the series, we have learned quite a bit about loops in PHP but this is obviously not the end of it. There are lots of advanced and interesting aspects related to loops that we must learn, like the break and continue statements and how to use them properly, nested loops and designing various loop related problems.

The next part of the series is surely going be very interesting as we would move deep into loops and design some really interesting and involving problems related to it. See you in the next episode and happy coding.

STAY UP TO DATE

Sign up today to stay informed with industry news & trends