Loops in PHP


Share

When we want a program to repeat the same sequence of code again and again
PHP’s various loop structures provide the perfect way to do this.

PHP has a four types Loops.


1) For Loop

For loop is most powerful loop.
it combines the abilities to set up variables as you enter the loop,
test for conditions while iterating loops, and modify variables after each iteration.

Syntax:-

for(initialization:condition;increment/decrement)
{
 code of block;
} 
    <?php
  for ($count = 1 ; $count <= 10 ; $count++) 
  echo "$count";
    ?> 
    OUTPUT:
    12345678910

2) While Loop

While loop execute the code until the expression is found to be FALSE.

Syntax:-

while(condition) { code of block; }
<?php
$count = 1;
while ($count <= 3) 
{
  print("$count times 12 is ",$count * 12 
)"; ++$count; } ?>
    OUTPUT:
    1 times 12 is 12
    2 times 12 is 24
    3 times 12 is 36

3) Do-While Loop

A slight variation to the while loop is the do...while loop,
used when you want a block of code to be executed at least once and made conditional only after that.

Syntax:-

do { 
code of block;
}
 while(condition);
<?php
$count = 1;
do
print("$count times 12 is ",$count * 12 
)"; while (++$count <= 12); ?>

Foreach Loop

Foreach loop used in PHP arrays.
Foreach loop use $ sign for assign value in array.

Syntax:-

foreach(array as $name)  
{
 code of block;
}
<?php
    $students = array(18,19,20,17);
    foreach($students as $age)
    echo $age;
?>