PHP TUTORIALS - PHP Loop Types
PHP Loop Types
ADVERTISEMENTS
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
|
ADVERTISEMENTS
Example
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo ("At the end of the loop a=$a and b=$b" );
?>
</body>
</html>
|
ADVERTISEMENTS
At the end of the loop a=50 and b=25
|
Syntax
while (condition)
{
code to be executed;
}
|
Example
<html>
<body>
<?php
$i = 0;
$num = 50;
while( $i < 10)
{
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
</body>
</html>
|
Loop stopped at i = 10 and num = 40
|
Syntax
do
{
code to be executed;
}while (condition);
|
Example
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
$i++;
}while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
|
Syntax
foreach (array as value)
{
code to be executed;
}
|
Example
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
|
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
|
Example
<html>
<body>
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
|
Example
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>
</body>
</html>
|
Value is 1
Value is 2
Value is 4
Value is 5
|