Sunday, 9 June 2013

LOOPS IN PHP

In this post I will be explaining three type of loop in php.

  1. for loop 
  2. while loop
  3. foreach loop
The for loop and the  while loop in php are exactly same as that of the C and C++. 
Source code illustrating the use of for loop:-
/********************************************************************************/
 <html>
                <head>
                                <title>constants</title>
                </head>
                <body>
                                <?php
                                               
                                                for($a=1;$a<=20;$a++)
                                                {
                                                                echo $a."<br/>";
                                                }
                                ?>
                </body>

</html>
/******************************************************************************/
Output:-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20



Now this program illustrates the use of while loops:-
Source Code:-
/******************************************************************************/


<html>
                <head>
                                <title>constants</title>
                </head>
                <body>
                                <?php
                                                $a=1;
                                                while($a <= 20)
                                                {
                                                                echo $a."<br/>";
                                                                $a++;
                                                }
                                ?>
                </body>
</html>
/******************************************************************************/
This program has the same output as that of the last program.

Now it's the turn of foreach loop.
Source code:-
/******************************************************************************/
<html>
                <head>
                                <title>constants</title>
                </head>
                <body>
                                <?php
                                                $arr=array(5,6,7,8,9,10,11,12,13);
                                                foreach($arr as $value)
                                                                echo $value."<br />";
                                ?>
                </body>

</html>
/*******************************************************************************/
Output:-
5
6
7
8
9
10
11
12
13

No comments:

Post a Comment