PHP

Loops in PHP

PHP Loops

There are mostly 3 loops are available on programming languages. But in php ther are 4 loops available.

  1. While loop
  2. Do while loop
  3. For loop
  4. Foreach loop

 

1. While loop

While loop start with the keyword while. While loop has a block, first it check the condition, if condition is true then block code execute

Syntax

while (condition is true) {
//write block code for execute
}

example

<?php

$i=1;

while($i <10){

echo $i;

$i++;

}

?>

Output

123456789

 

2. Do … while loop

The do… while loop is a control flow statement which execute block at least once after that it check the condition. And repeat the loop.

The do while loop always execute or run the code of block at least one time.

Syntax

do {
//write block code for execute
} while (condition is true);

Example

<?php
$i = 1;

do {
echo $i;
$i++;
} while ($x <10);
?>

Note : The do … while loop first execute the code after that check the condition on below

3. For loop

The for loop in php first creates a variable and assigned integer value, after that it will check the condition, if condition is true it will execute the code or program then increment or decrement the value of variable and then check the condition if condition is true execute the code this process is run till the condition is false.

Syntax

for (init variable; condition is true; increment/decrement variable) {
//write block code for execute
}

There are 3 points in for loop

  1. init variable: Initialize the loop variable value
  1. check the condition: check the condition, if TRUE, the loop continues. If FALSE, the loop ends.
  2. increment / decrement variable: Increases or decrement the variable value.

Example

<?php
for ($i = 10; $i >= 1; $i–) {
echo $i;
}
?>

 

4. Foreach loop

The foreach loop of php works only on arrays, and is used to each key/value pair in an array.

Syntax

foreach ($array as $key=>$value) {
//write block code for execute
}

Example

<?php
$i = array(1, 2, 3, 4, 5, 6, 7, 8);

foreach ($i as $val) {
echo $val;
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *