The WHILE loop seems very useful when we want to execute a piece of code
for several times. The loop keep executing the code until certain condition is reached.
This is one of the most useful command in PHP.
If you want to execute a piece of code for several times without retyping,
You can make use of a while loop. For example if you have to print "Hello World" 5
times, you can use the following code
In the first two lines we are just setting variables. $time holds number of times
the code to be executed. $x is used to count the number of times the code has executed.
Then there comes the while loop statement, This tells the processor to execute the code
while $x is less than or equals $time. And this statement is followed by the code
enclosed within { }.
Arrays in PHP
An array can hold more than one value, These are special variables used in almost many
programming languages. Values in array are stored in its own numbered 'space'.
Arrays are very useful specially when using WHILE loop.
Initialising an array is slightly different from initialising a normal variable.
Setting up an array is slightly different to setting up a normal variable. In this example
let us set up an array with 5 names in it:
Here the array elements are numbered from 0. To insert a value to the array you must
specify the location in the array by putting a number in the brackets [ ].
Reading From An Array
Reading data from the array is very simple, it is same as we put in data. All that we
have to do is refer to array and the number of the data item which we want to read out
from the array. So if i want to print the third name of the array, then can use the following code.
echo "The third name is $names[2]";
Which would output:
The third name is Steven
Using Arrays And Loops
One of the best use of loop is to display out all the elements in an array.
Loop is used to fetch the elements in an array if the array has huge number of elements.
For example consider the following array.
Name 1 is John
Name 2 is Paul
Name 3 is Steven
Name 4 is George
Name 5 is David
In the code we have assigned $namenumber as "1" and $x have assigned "0", because the counting
of name should start from "1" and the first name stored in the array is in position "0".
The echo statement is executed till $x becomes greater than $number, And thus all the names
in array are read out.
Share And Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.