Practical No 03: PHP Looping Structures
Practical No 03: PHP Looping Structures
Practical No 03: PHP Looping Structures
A. Practical Significance
Often when code is written, the same block of code to run over and over again for a certain number
of times. So, instead of adding several almost equal code-lines in a script, we can use loops. Loops
are used to execute the same block of code again and again, as long as a certain condition is true.
C. Resources used
Sr. Instrument/Machine
Specifications Quantity Remark
No. /Software
Windows 8.1 (64-Bit), Intel (R) Core
1 Desktop PC 01 Nil
(TM) i3 CPU @2.40 GHz, 4GB RAM
Xampp v3.2.4, Package contains
2 Xampp 01 Nil
Apache + MariaDB + PHP + Perl
Notepad++ and
3 Editor and Browser 01 and 01 Nil
Google Chrome
D. Program Code
a) Write a php program to find the sum of 1 to n numbers using while loop.
<!DOCTYPE html>
<html>
<head>
<title> while loop </title>
</head>
<body>
<?php
$n = 10;
$i = 1;
<body>
<?php
$arr = array(89, 45, 67, 83, 48, 29, 58, 74);
echo "Array Element: ";
foreach($arr as $val) {
echo $val . " ";
}
?>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title> foreach loop </title>
</head>
<body>
<?php
for($i=1; $i<=5; $i++) {
for($j=1; $j<=$i; $j++) {
if($j % 2 == 1)
echo "A ";
else
echo "B ";
}
echo "</br>";
}
?>
</body>
</html>
<body>
<?php
$subjects = array("1"=>"English", "2"=>"Hindi",
"3"=>"Sanskrut", "4"=>"Science", "5"=>"Mathematics");
foreach($subjects as $value)
{
echo $value . "</br>";
}
?>
</body>
</html>
Output
English
Hindi
Sanskrut
Science
Mathematics
b) Describe foreach loop in php.
The foreach loop - Loops through a collection of elements for each element in that collection. The
foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.
G. Exercise:
a) Write a php program to display numbers between 1 to 100 which are divisible by 7.
<!DOCTYPE html>
<html>
<head>
<title> for loop </title>
</head>
<body>
<?php
for($i=1; $i<=100; $i++) {
if($i % 7 == 0) {
echo $i . " ";
}
}
?>
</body>
</html>
Output 7 14 21 28 35 42 49 56 63 70 77 84 91 98
while($i != 0) {
$digit = $i % 10;
$sum = $sum + ($digit ** 3);
$i = $i / 10;
}
if($sum == $num) echo "Armstrong number.";
else echo "Not Armstrong number.";
?>
</body>
</html>
Assessment Scheme
4 Presentation of Output 20 %
Assessment
Date Signature of
Marks Obtained
Subject Teacher
Process Related Product Related
Total (50 Marks)
(30 Marks) (20 Marks)