Deal with while loop in php

Deal with while loop in php : Day#3

Today we are going to learn about loop. Basically, we uses 2 types of loop frequently. One is “FOR” loop and another is “WHILE” loop. I’m going to discuss about “WHILE” loop today and upcoming tutorial I’ll discuss about “FOR” loop.

The WHILE loop is one of the most useful commands in PHP. It is also quite easy to set up and use. A WHILE loop will, as the name suggests, execute a piece of code until a certain condition is met.

Repeat Elements specific number Of Times

If you have a piece of code which you want to repeat several times without retyping it, you can use a while loop. For instance if you wanted to print out the words “Hello World” 5 times you could use the following code:

$times = 5;
$x = 0;
while ($x < $times) {
echo "Hello World"; 
++$x;
}

The first two lines are just setting the variables. The $times variable holds the number of times you want to repeat the code. The $x variable is the one which will count the number of times the code has been executed. After these is the WHILE line. This tells the computer to repeat the code while $i is less than $times (or to repeat it until $i is equal to $times). This is followed by the code to be executed which is enclosed in { }.

After the echo line which prints out the text, there is another very important line:

++$x;

What this does is exactly the same as writing:

$x = $x + 1;

It adds one to the value of $x. This code is then repeated (as $x now equals 1). It continues being repeated until $x equals 5 (the value of times) when the computer will then move on to the next part of the code.

Video Tutorial:

Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!

Quiz Time:

What is the correct form of PHP?

Total 0 Votes
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Comment

Back To Top