PHP - LOOPS
Hello All...
welcome every one. I'm going to start PHP lectures for Very Beginners, who
wants to learn PHP from very beginning. No matter if you do not have any basic
programming concept. If you follow my tutorials I hope you will surely get some
how good knowledge of PHP.
Today our
Topic is
LOOPS
The term
`loop` is defined as “Repetition of anything”. Here in PHP we use loops when we
have to print something multiple times by writing them just single time within
a loop.
In almost
every programming language there are 4 types of loops.
1- While Loop
2- Do-while Loop
3- For Loop
4- For each Loop
The last one
For each loop will be studied in next coming topic `Arrays` but here we will
focus of first three types of loops.
i-
While loop: This loop works when the specified
condition defined in loop syntax is true.
Here is
simple syntax
while( condition )
{
Code you wants to execute
}
The code
within the curly braces will be executed if the condition defined in the above
brackets is true. Let’s take an example of first while loop.
First start
the php
<?php
$a = 1;
while($a < 10){
echo $a;
$a++;
}
?>
Description
of above code:
First of all
we have declared a variable named `a` and assigned value of 1
After then
while loop is started with `while` keyword and inside the brackets there is
condition defined that $a declared above is less than 10 or not if it’s less
than 10 means condition is true if condition is true then remaining part of
code will be executed. After while condition is true there is echo statement
that prints $a variable and $a will be printed unless and until while
condition becomes false. And in last $a++ this is called an increment
operator. Increment operator increases the value by adding +1 in the defined
value. So variable a will also increase by means of +1.
Here is the code and result of it
The result
is up to 9 because if it comes to 10 and look at the condition that says $a
< 10 when it becomes 10 then 10 < 10 this condition becomes false and the
code execution is stopped. While loop executes the code until condition is
true. In simple while loop first checks the condition and then executes the
code. Similarly you can print multiple statements using while loop in `echo`
statement by creating your own login.
Thanks Guys.
Any thing missing or any question from this topic you can comment below, I will
be trying to solve and answer your question.
Our Next
topic will be `do-while Loop`.
Good Luck J
No comments:
Post a Comment