Loops in PHP

Loops in PHP


Published at - Aug 13, 2021

This guide is to provide all information about the loops available in PHP, like any other programming language PHP also have loops. Loops available in PHP are as follows –

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

For Loop – For loop in PHP used to repeat the code execution number of times defined by the user. It takes a total of 3 arguments and repeats until conditions satisfied.

Example : Print all numbers from 1 to 10

<?php
	for($i = 1; $i <= 10; $i++){
    	echo $i.'<br>';
  	}
?>

Output :

1
2
3
4
5
6
7
8
9
10

Foreach loop Foreach loop is a special loop provided by the PHP it workes on array element and repeats total length times of array.

Example : Print all elements of given array

<?php
	$array = [1,2,3,4,5,6,7,8,9,10];
	foreach($array as $a){
		echo $a.'<br>';
	}
?>

Output :

1
2
3
4
5
6
7
8
9
10

Do While loop – The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.

Example :

<?php
$x = 1;

do {
  echo "The number is: $x <br>";
  $x++;
} while ($x <= 5);
?>

Output :

The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

While loop – The while loop will always first check the condition, and repeat the loop while the specified condition is true.

Example :

<?php
$x = 1;

while ($x <= 5){
  echo "The number is: $x <br>";
  $x++;
}
?>

Output :

The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

Thank you for reading.



About author

Harendra
Harendra Kanojiya

Hi I'm Harendra Kumar Kanojiya. Currently I am FSD (Full-stack developer) and I have expertise with Angular ,PHP, Node JS, Laravel, Codeigniter and front end. Done few live projects and portfolio work in above.



Follow Us

Follow us on facebook Click Here

Facebook QR
Scan from mobile
Join our telegram channel Click Here
Telegram QR
Scan from mobile