welcome to tutorialfamily

php loop

PHP loop – used for check condition and execute the entry.


PHP loops

We can check various condition and execute the code and print all entry using loops statement.

  • While loop
  • Do While loop
  • For loop
  • Foreach loop

While loop

Using while loop executes a block of code when a condition is true.
while loop is also called entry control loop it means it check condition first after executes
block of code the.

Below the example is given.


While loop



<!DOCTYPE html>
<html>
<head>
	<title>While loop</title>
</head>
<body>
// While loop increment
<?php
	$x=1;
	while($x<=10)
	{
		echo $x."
	";
		$x++;
	}
?>
// While loop decrement
<?php
	$x=10;
	while($x>=1)
	{
		echo $x."
	";
		$x--;
	}
?>							
</body>
</html>

output

do while loop

Using do while loop executes a block of code when a condition is true.
It will check the condition, if condition is false again repeat the loop and check the condition, when condition is true the code will be execute.

Below the example is given.


do while loop



<!DOCTYPE html>
<html>
<head>
	<title>do while loop</title>
</head>
<body>
// do while loop increment
<?php

	$x=1;
	do
	{
		$x++;
		echo $x."
     ";
		$x++;
	}while($x<=10);

?>	
// do while loop decrement
<?php

	$x=10;
	do
	{
		$x--;
		echo $x."
    ";
		$x--;
	}while($x>=1);

?>							
</body>
</html>

output

For loop

For loop use to repeat many time loop.

  • Initialization
  • Condition
  • Increment/decrement

For loop



<!DOCTYPE html>
<html>
<head>
	<title>For loop</title>
</head>
<body>
// Syntax For loop
<?php
	for(initialization; condition; increment/decrement)
	{
		code to be executed
	}
?>
// For loop increment
<?php
	for($i=1; $i<=15; $i++)
	{
		echo $i;
	}
?>
// For loop decrement
<?php
	for($i=15; $i>=0; $i--)
	{
		echo $i;
	}
?>							
</body>
</html>

output

Foreach loop

Foreach loop use to get value as a output in easy way.

First of store the array of value in variable.

Variable declare as a value in foreach statement.


Foreach loop



<!DOCTYPE html>
<html>
<head>
	<title>Foreach loop</title>
</head>
<body>
// Syntax Foreach loop
<?php
	foreach (variable_name as value) // variable store the array
	{ 
	  code to be execute
	}
?>
// Foreach loop
<?php
	$x=array("Information","Technology","Tutorial family");
	foreach($x as $value)
  {
	echo $value;
  }
?>
						
</body>
</html>

output

Our Content