Ticker

6/recent/ticker-posts

PHP (Loop)

LOOP IN PHP

INTRODUCTION
Loops are also known as “Iterative statement” because it repeats itself until the loop’s condition would be true.

In PHP,  there are four types of loops, which described below.
1. While loop
2. Do while loop
3. For loop
4. Foreach Loop


PARTS OF LOOP
Any loop can be classify into three sub parts, which are described below.

1. Initialization: this part is responsible to initialize the loop’s variable.               
Example ($a=0)

2. Test condition: this statement is used to implement the test criteria and responsible to stop Loop’s execution.  Ex. while ($a<10)

3. Increment or decrement: these statements are used to change the value of loop’s variable.

Increment examples
$a++, $a=$a+1, $a=$a+2

Decrement examples
$a--, $a=$a-1, $a=$a-2

Increment and decrement statements can be also classify in two sub categories.
Pre increment (Example: ++$a)
Post increment (Example: $a++)

PRE AND POST INCREMENT EXAMPLES 
int $a=10
echo($a++);

echo(++$a);
$a=$a+2;
echo($a);

Output
10
12
14


WHILE AND DO WHILE LOOP (DIFFERENCES)

WHILE LOOP
In the while loop the condition is tested first and then the statements are executed if the condition turns out to be true.  A do while is used for a block of code that must be executed at least once.
int $a=1;
while($a >10)
{
echo($a);
$a=$a+1;
}

DO WHILE LOOP
In do while the statements are executed for the first time and then the conditions
are tested, if the condition turns out to be true then the statements are executed again.
 A do while loop runs at least once even though the condition given is false while loop do not run in case the condition given is false.
$a=1;
do
{
echo(“<br>”,$a);
$a=$a+1;
}
while($a >10);

Post a Comment

0 Comments