codescracker


php

PHP for Loop



« Previous Tutorial Next Tutorial »


PHP for loop is used to execute a block of code, specified number of times. Here is the general form to use for loop in PHP:

for(initialization-counter; condition-checker; incrementation)
{
	code to be executed here;
}

Here is the explanation of the above parameters of the for loop in PHP:

PHP for Loop Example

Here is an example, uses for loop in PHP. This example displayes the numbers from 0 to 10 and the table of 2.

<!DOCTYPE html>
<html>
<head>
	<title>for Loop Example in PHP</title>
</head>
<body>
<?php
	echo "<h2>Printing number from 1 to 10</h2>";
	for($x = 0; $x <= 10; $x++)
	{
		echo $x;
		echo " ";
	}
	echo "<h2>Printing table of 2</h2>";
	for($x = 2; $x <= 20; $x=$x+2)
	{
		echo $x;
		echo " ";
	}
?>
</body>
</html>

Here is the output produced by the above PHP script:

PHP for Loop

Let's take another example also demontrates for loop in PHP with three different-different type.

<!DOCTYPE html>
<html>
<head>
	<title>PHP for Loop Example - CodesCracker</title>
</head>
<body>
<?php
	// first type of for loop in PHP
	for($i=0; $i<10; $i++)
	{
		echo $i;
		echo " - ";
	}
	echo "<hr/>";
	// second type of for loop in PHP
	for($i=0; ; $i++)
	{
		if($i>9)
		{
			break;
		}
		echo $i;
		echo " - ";
	}
	echo "<hr/>";
	$i = 0;
	// third type of for loop in PHP
	for(; ;)
	{
		if($i>9)
		{
			break;
		}
		echo $i;
		echo " - ";
		$i++;
	}
?>
</body>
</html>

The above for loop example in PHP will produce the following output:

php for loop example

As you can realize from the above for loop example in PHP, if you remove the condition part of the for loop, then you must have to put the condition inside the for loop possibly using the if statement, otherwise the loop will go for infinity.

Let's take one more example on for loop in PHP.

<!DOCTYPE html>
<html>
<head>
	<title>PHP for Loop Example - CodesCracker</title>
</head>
<body>
<?php
	$num = 2;
	for($i=1; $i<=10; $i++)
	{
		echo $num * $i;
		echo "<br/>";
	}
?>
</body>
</html>

The output of above for loop program is shown below:

for loop in php

« Previous Tutorial Next Tutorial »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test