PHP Loop Function


 

PHP Loop Function

PHP Loop: In this tutorial you will come to learn about loops supported by PHP, such as: for, while, do-while, foreach etc. in addition this tutorial also provides an example of recursion.

PHP Loop: In this tutorial you will come to learn about loops supported by PHP, such as: for, while, do-while, foreach etc. in addition this tutorial also provides an example of recursion.

PHP LOOP Function

In programming language a loop is a language construct which allows statements within to execute again and again. Loop can be achieved both in iterative(for, while, do-while) and recursive method(when a function or method calls itself).

PHP provides for, while, do-while, and foreach loop. Following examples will help you to learn loops:

Example 1(For, While, Do-While):

<?php

echo "<b>Using For-loop print 1 - 10</b><br/>";

for($a=1;$a<11;$a++)

    echo $a."<br/>";

echo "<b>Using While loop print 11 - 20</b><br/>";

while($a < 21)

{

echo $a."<br/>";

$a++;

}

echo "<b>Using Do-While loop print 21 - 30</b><br/>";

do

{

echo $a."<br/>";

$a++;

}while($a<31);

?>

Output:

Using For-loop print 1 - 10
1
2
3
4
5
6
7
8
9
10
Using While loop print 11 - 20
11
12
13
14
15
16
17
18
19
20
Using Do-While loop print 21 - 30
21
22
23
24
25
26
27
28
29
30

Example 2 (Recursion):

<?php

function factorial($f)

{

if   ($f==1)

            return 1;

else

return ($f * factorial($f-1));

0

}

$f=5;

echo "<b>Factorial of $f is =".factorial ($f);

1

?>

Output:

Factorial of 5 is =120

Example 3(Foreach):

2

<?php

$array=array("This","is","an","array");

echo "<b>Actual value of \$array is as follows:</b><br/>";

3

var_dump($array);

echo "<br/><b>Individual value of \$array is as follows:</b><br/>";

$a=1;

4

foreach($array as $val)

{

    echo $a." Value of \$array is= ".$val."<br/>";

5

    $a++;

}

?>

6

Output:

Actual value of $array is as follows:
array(4) {
  [0]=>
  string(4) "This"
  [1]=>
  string(2) "is"
  [2]=>
  string(2) "an"
  [3]=>
  string(5) "array"
}

Individual value of $array is as follows:
1 Value of $array is= This
2 Value of $array is= is
3 Value of $array is= an
4 Value of $array is= array

 

Ads