Day 5: while, for and switch-case

Loop is use to do repetitive work until task has not been completed.

1) Understanding “while” Control Structure

while is the simplest type of loop in PHP, statement inside the while loop executes until condition in ture.

Syntax:
while (condition) {
statement here will execute when condition is true.
}

Program 13: Display series 1-10.

<?php
$a = 1;
while($a < 11) { echo $a.","; $a++; } ?>

OUTPUT:
1,2,3,4,5,6,7,8,9,10,


Explanation: in above example until the value of $a less then 11, statement will execute again and again and value of “$a” will display with increment.

Program 14: Display table of 2 with while.

<?php
$a = 1;
$tab = 2;
while($a <= 10) { echo $tab." x ".$a." = ".$tab*$a; echo "
“;
$a++;
}
?>

OUTPUT:
tab


Program 15: Display reverse of digit with “while”.

<?php
$a = 123;
while($a > 0) {
$r = $a % 10;
$rev = $rev * 10 + $r;
$a = intval($a / 10);
}
echo “Reverse of digit is “.$rev;
?>

OUTPUT:
Reverse of digit is 321


2) Understanding “for” Control Structure

For is the most complex loop in php.
Syntax:
for (assignment; condition; increment/decrement) {
statement here will execute when condition is true.
}

Program 16: Display series 10-1.

<?php
for($a=10; $a>0; $a–) {
echo $a.”,”;
}
?>

OUTPUT:
10,9,8,7,6,5,4,3,2,1,


Program 17: Display series 1-10.

<?php

for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); ?>


OUTPUT:
12345678910


Program 18: Use of break with for-loop.

<?php

for ($i = 1; $i<10; $i++) { if ($i > 5) {
break;
}
echo $i;
}
?>


OUTPUT:
12345


Note: break is used to discontinue OR exit from loop.

Program 19: Nested for-loop.

<?php
for($a=1; $a<=5; $a++) { for($b=1; $b<=5; $b++) { echo $a; } echo "<br/>"; } ?>

OUTPUT:
11111
22222
33333
44444
55555


3) Understanding “switch – case” Control Structure

Syntax:
switch (a) {
case 1: code to be executed if a=1; break;
case 2: code to be executed if a=2; break;
case 3: code to be executed if a=3; break;

default: code to be executed if a is different from all labels;
}

Program 20: Choice of day.

<?php
$favcDay = 5;
switch ($favcDay) {
case 1: echo “Day is Monday!”; break;
case 2: echo “Day is Tuesday!”; break;
case 3: echo “Day is Wednesday!”; break;
case 4: echo “Day is Thrusday!”; break;
case 5: echo “Day is Friday!”; break;
case 6: echo “Day is Saturday!”; break;
case 7: echo “Day is Sunday!”; break;
default: echo “This is not a Day!”;
}
?>

OUTPUT:
Day is Friday!


Assignments:

  • Write a program to find a sum of digit in while.
  • Write a program to display below output in for loop
    *
    * *
    * * *
    * * * *

Leave a Reply