3 Practical

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Web Based Application Development Using PHP(22619)

Practical No. 3: Write a PHP Program to demonstrate use of Looping structures using-
a) While Statement, b) Do-while statement, c) For Statement, d) ForEach Statement

I. Practical Significance
Loop in PHP is used to execute a statement or a block of statements, multiple times until and
unless a specific condition is met. This helps the user to save both time and effort of writing
the same code multiple times.

II. Minimum Theoretical Background

PHP Loops:
In PHP, we have the following loop types:
Loop Description Syntax

while Loops through a block of code as long as the while (if the condition is
specified condition is true true) {
// code is executed
}

do...while Loops through a block of code once, and then do {


repeats the loop as long as the specified condition
is true //code is executed

} while (if condition is


true);

for Loops through a block of code a specified number for (initialization


of times expression; test
condition; update
expression) {
// code to be executed
}

foreach Loops through a block of code for each element in foreach (array_element as
an array value) {
//code to be executed
}

III. Exercise:
1) While Statement
Input:
<?php
// While Statement
$a=1;
echo "<br><br><b>-----------While Statement--------</b>";
while($a<=5):
echo "<br>$a";
$a++;
endwhile;
?>

1
Web Based Application Development Using PHP(22619)

Output:
---------------------While Statement-----------------
1
2
3
4
5

2) Do While Statement
Input:
<?php
//Do While Statement
echo "<br><br><b>--------Do While Statement--------</b>";
$a=6;
do
{ echo "<br>$a";
$a++;
}
while($a<=10);
?>
Output:
---------------------Do While Statement-------------------
6
7
8
9
10
3) For loop
Input:
<?php
//For Loop
echo "<br><br><b>--------For Loop------------------</b>";
for($a=11;$a<=15;$a++):
echo "<br>$a";
endfor;
?>
Output:
------------------------For Loop--------------------------
11
12
13
14
15

2
Web Based Application Development Using PHP(22619)

4) For Each
Input:
<?php
//For Each Loop (for indexed array
echo "<br><br><b>-ForEach Loop(for indexed array)--</b>";
$colors = array(16, 17, 18,19);

// Loop through colors array


foreach($colors as $value):
echo "<br>$value";
endforeach;
?>
Output:
---------For Each Loop (for indexed array)-----------------
16
17
18
19

IV. Conclusion
Thus we have successfully completed the given experiment based on:
Program to demonstrate use of Looping structures using-
a) While Statement, b) Do-while statement, c) For Statement, d) ForEach Statement

You might also like