0% found this document useful (0 votes)
32 views49 pages

LECTURE 5-Flow Control-Looping

The document discusses various PHP looping statements like for, foreach, while and nested loops. It provides the syntax and examples of each loop. Key loops covered include for to iterate a known number of times, foreach to iterate arrays, while to iterate an unknown number of times until a condition is met.

Uploaded by

Hemalatha B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views49 pages

LECTURE 5-Flow Control-Looping

The document discusses various PHP looping statements like for, foreach, while and nested loops. It provides the syntax and examples of each loop. Key loops covered include for to iterate a known number of times, foreach to iterate arrays, while to iterate an unknown number of times until a condition is met.

Uploaded by

Hemalatha B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Sri Krishna Arts And Science College

Department of ICT

Course Title: PHP & MYSQL


Course Code: 19CSS22
Class : III BSc – Computer Technology “A”
Google Class room Code: 7cxe5v3

Online Material
Lecture 5: Flow Control - Looping

Facilitator
B.Hemalatha

Assistant Professor

Department of Computer Technology


SKASC
Objective
 For
 Foreach
 While
 Do While
 Declare
 Exit and return
 Goto.
Text Books
1. Rasmus Lerdorf, Kevin Tatroe, Bob Kaehms, RicMcGredy
(2020), Programming PHP, O’REILLY(SPD), 4th Edition.
2. Vikram Vaswani, 2017, “PHP A Beginners Guide”, Tata
McGrawHill
3. Lee Babin, Nathan A. Good, Frank M. Kromann, Jon
Stephens (2013), “PHP 5Recipes, A problem solution
approach”, après
Looping statements

Topic: Looping statements


Reference: Dani Krossing Channel
Looping statements

Topic: Looping statements


Reference: Atif Nazeem Channel
For Loop

 Can be used to traverse set of code for the specified number


of times.
 It should be used if the number of iterations is known
otherwise use while loop.
 This means for loop is used when you already know how
many times you want to execute a block of code.
 It allows users to put all the loop related statements in one
place.
Syntax

for(initialization; condition; increment/decrement)


{
//code to be executed
}
Parameters
 Initialization - Initialize the loop counter value.
 The initial value of the for loop is done only once.
 This parameter is optional.
Syntax

 Condition - Evaluate each iteration value.


 The loop continuously executes until the condition is false.
 If TRUE, the loop execution continues, otherwise the
execution of the loop ends.
 Increment/decrement - It increments or decrements the
value of the variable.
For Loop
Example
<?php
for($n=1;$n<=10;$n++)
{
echo "$n<br/>";
}
1
?> 2
3
4
5
6
7
8
9
10
Example
▪ Printing numbers from 1 to 9 in four different ways using
for loop.
<?php
/* example 1 */
for ($i = 1; $i <= 9; $i++) {
echo $i;
}
echo "</br>";
Example
▪ Printing numbers from 1 to 9 in four different ways using
for loop.
/* example 2 */
for ($i = 1; ; $i++)
{
if ($i > 9) {
break;
}
echo $i;
}
echo "</br>";
Example
▪ Printing numbers from 1 to 9 in four different ways using
for loop.
/* example 3 */
$i = 1;
for (; ; )
{
if ($i > 9)
{ break;
}
echo $i;
$i++;
}
echo "</br>";
Example
▪ Printing numbers from 1 to 9 in four different ways using
for loop.
/* example 4 */

for ($i = 1, $j = 0; $i <= 9; $j += $i, print $i, $i++);


?>

123456789
123456789
123456789
123456789
Nested For Loop
 for loop inside for loop in PHP, it is known as nested for loop.

 The inner for loop executes only when the outer for loop
condition is found true.
 In case of inner or nested for loop, nested for loop is executed
fully for one outer for loop.
 If outer for loop is to be executed for 3 times and inner for loop
for 3 times, inner for loop will be executed 9 times (3 times for
1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd
outer loop).
Nested For Loop
<?php

for($i=1;$i<=3;$i++){

for($j=1;$j<=3;$j++){
11
echo "$i $j<br/>"; 12
13
21
} 22
23
} 31
32
?> 33
For Each Loop
 for each loop is used to Example
traverse array elements. <?php
 Syntax $season=array("summer","winte
foreach( $array as $var ) r","spring","autumn");
{ foreach( $season as $arr ){

//code to be executed echo "Season is: $arr<br />";

} }

?>Season is: summer ?>


Season is: winter
Season is: spring
Season is: autumn
foreach loop

 Used to traverse the array elements.


 It works only on array and object.
 It will issue an error if you try to use it with the variables of
different datatype.
 The foreach loop works on elements basis rather than index.
 It provides an easiest way to iterate the elements of an array.
 In foreach loop, we don't need to increment the value.
Syntax
foreach ($array as $value) {

//code to be executed

Syntax

foreach ($array as $key => $element) {

//code to be executed

}
Flowchart
Example 1
PHP program to print array elements using foreach loop.

<?php

//declare array

$season = array ("Summer", "Winter", "Autumn", "Rainy");

//access array elements using foreach loop

foreach ($season as $element) {

echo "$element";

echo "</br>"; Summer


Winter
Autumn
} Rainy

?>
Example 2
 PHP program to print associative array elements using
foreach loop.

<?php

//declare array

$employee = array (

"Name" => "Alex",

"Email" => "[email protected]",

"Age" => 21,

"Gender" => "Male" );


Example 2
//display associative array element through foreach loop

foreach ($employee as $key => $element) {

echo $key . " : " . $element;

echo "</br>";

?>
Name : Alex
Email : [email protected]
Age : 21
Gender : Male
Example 3
 Multi-dimensional array

<?php
//declare multi-dimensional array
$a = array();
$a[0][0] = "Alex";
$a[0][1] = "Bob";
$a[1][0] = "Camila";
$a[1][1] = "Denial";
Example 3
//display multi-dimensional array elements through foreach loop
foreach ($a as $e1) {
foreach ($e1 as $e2) {
echo "$e2\n";
}
}
?>

Alex Bob Camila Denial


Example 4
Dynamic array
<?php
//dynamic array
foreach (array ('j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't') as $elements) {
echo "$elements\n";
}
javatpoint
?>
While Loop
 Loop executes a block of code repeatedly until the condition
is FALSE.
 Once the condition gets FALSE, it exits from the body of loop.

 It should be used if the number of iterations is not known.

 The while loop is also called an Entry control loop because


the condition is checked before entering the loop body.
 This means that first the condition is checked.

 If the condition is true, the block of code will be executed.


While Loop
Syntax
while(condition)
{
//code to be executed
}
Alternative Syntax
while(condition):
//code to be executed
endwhile;
Example
<?php
1
$n=1; 2
3
while($n<=10){ 4
5
echo "$n<br/>"; 6
7
8
$n++; 9
10
}

?>
Alternative Example
<?php
1
$n=1; 2
3
while($n<=10): 4
5
echo "$n<br/>"; 6
7
8
$n++; 9
10
endwhile;

?>
Example
Example of printing alphabets using while loop.
<?php
$i = 'A';
while ($i < 'H') A
{ B
C
echo $i; D
$i++; E
echo "</br>"; F
G
}
?>
Nested While Loop
 While loop inside another while loop in PHP, it is known as
nested while loop.
 In case of inner or nested while loop, nested while loop is
executed fully for one outer while loop.
 If outer while loop is to be executed for 3 times and nested
while loop for 3 times, nested while loop will be executed 9
times (3 times for 1st outer loop, 3 times for 2nd outer loop
and 3 times for 3rd outer loop).
Example
<?php

$i=1;
11
12
while($i<=3){ 13
21
$j=1; 22
23
while($j<=3){ 31
32
echo "$i $j<br/>"; 33

$j++; }

$i++;

?>
do-while loop
 Is used to execute a set of code of the program several
times.
 If you have to execute the loop at least once and the
number of iterations is not even fixed, it is recommended
to use the do-while loop.
 It executes the code at least one time always because the
condition is checked after executing the code.
 The do-while loop is very much similar to the while loop
except the condition check.
do-while loop
 The main difference between both loops is that while loop
checks the condition at the beginning, whereas do-while
loop checks the condition at the end of the loop.

Syntax

do{

//code to be executed

}while(condition);
Example
<?php

$n=1;
1
2
do{ 3
4
echo "$n<br/>"; 5
6
$n++; 7
8
}while($n<=10); 9
10
?>
Difference between while and do-while loop

while Loop do-while loop

The while loop is also named as The do-while loop is also named
entry control loop. as exit control loop.

The body of the loop does not The body of the loop executes at
execute if the condition is false. least once, even if the condition is
false.

Condition checks first, and then Block of statements executes first


block of statements executes. and then condition checks.

This loop does not use a semicolon Do-while loop use semicolon to
to terminate the loop. terminate the loop.
Declare
 Declare statement allows you to specify execution directives
for a block of code.
 The structure of a declare statement is:

declare (directive)

statement
 Currently, there is only one declare form, the ticks directive.

 Using it, you can specify how frequently (measured roughly in


number of code statements) a tick function registered with
register_tick_function( ) is called.
Declare
 Example:

register_tick_function("some_function");

declare(ticks = 3) {

for($i = 0; $i < 10; $i++)

{ // do something

}
 In this code, some_function( ) is called after every third
statement is executed
Exit and return
▪ The exit statement ends execution of the script as soon as it is
reached.
▪ The return statement returns from a function or (at the top level
of the program) from the script.
▪ The exit statement takes an optional value.

▪ If this is a number, it's the exit status of the process.

▪ If it's a string, the value is printed before the process


terminates.
▪ The exit( ) construct is an alias for die( ):
Exit and return
$handle = @mysql_connect("localhost", $USERNAME,
$PASSWORD);

if (!$handle)

die("Could not connect to database");

This is more commonly written as:

$handle = @mysql_connect("localhost", $USERNAME,


$PASSWORD) or die("Could not connect to database");
Goto
 goto - which is the operator of unconditional transition.

 It used to go into another area of the code.

 A place where you must go to the program is indicated by the


label (a simple identifier), followed by a colon.
 For the transition after the goto statement is put the desired
label .
Goto
<?php
for($i = 0; $i < 5; $i ++)
{
if($x == 2)
{
goto end;
}
echo $i . " ";
}
end:
?>
// output 0 1
Goto
 The target label must be within the same file and context,
which means that you cannot jump out of a function or
method.
 You also cannot jump into any loop or switch structure. You
may jump out of these .
Assignment
Output $i as long as $i is less than 6.

$i = 1;

______($i < 6)

echo $i;

$i++;
Assignment
Create a loop that runs from 0 to 9.

_____($i = 0;$i < 10; _____)

echo $i;

}
Assignment
Create a loop that runs from 0 to 9.

$colors = array("red", "green", "blue", "yellow");

_____($colors _______ $x)

echo $x;

}
Do It Yourself

Click
THANK YOU

You might also like