FOR LOOP AND FOREACH LOOP IN PHP

php loops,loops in php PHP Loops are most important in php programming.

Because Php loops provides  a lot of services like:

Execute a statement specific number of times.Reduce the length of program code & reduce the  execution or run time also check various condition before execute a code.

Types of Loops used in PHP:

Mainly four kind of loops are used in PHP these are:

1.FOR Loop

2.FOREACH Loop

3.While Loop

4.Do While Loop

1.FOR Loop:

FOR Loop is used in PHP to run a similar  code a set of number of times.

Syntax Of for loop:

for (initial expression,Condition check expression,increment/decrement  )
{
a statement  have to write here that is executed ;


}

I hope you must understand about for loop from following interface:

php loop descriptions

Example of for loops with php code:

<html>
<body>

<?php
for ($j=1; $j<=3; $j++)
{
echo "wel come to php LOOP when value of j is:" . $j . "<br>";
}
?>

</body>
</html>

Output of the above code looks like below:

wel come to php LOOP when value of j is:1
wel come to php LOOP when value of j is:2
wel come to php LOOP when value of j is:3

 2.FOREACH Loop:

foreach loop  is used in PHP to acsses  all of the elements of an array.

Syntax of foreach loops:

foreach ($array_name as $new avriable or $value)
{
a statement have to execute here;
}

Example of foreach loops with php code:

<html>
<body>

<?php

$dollar = array(1,2,3);

foreach ($dollar as $earn)
{
echo "Your new earning is " . $earn*15 . "<br>";
}
?>
</body>
</html>

Output of the above code is:

Your new earning is 15
Your new earning is 30
Your new earning is 45

Related Post: