"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Tuesday, June 12, 2018

What is Looping in PHP


LOOPING
·         loops are used to execute a set of statements repeatedly until a particular condition is satisfied.
·         A sequence of statements are executed until a specified condition is true.
·         This sequence of statements to be executed is kept inside the curly braces { } known as the Loop body.
·         After every execution of loop body, condition is verified, and if it is found to be true the loop body is executed again.
·         When the condition check returns false, the loop body is not executed.

PHP supports following four loop types.
·        for − loops through a block of code a specified number of times.
·        foreach − loops through a block of code for each element in an array.
·        while − loops through a block of code if and as long as a specified condition is true.
·        do...while − loops through a block of code once, and then repeats the loop as long as a special condition is true.
continue and break keywords are used to control the loops execution.
1.For Loop:
A for-loop (or simply for loop) is a control flow statement for specifying iteration, which allows code to be executed repeatedly. ...
For-loops are typically used when the number of iterations is known before entering the loop.
The syntax of a for loop in php is −
for ( inititialization ; condition; increment ) {
   statement(s);
}

Flow Diagram of For Loop:

Here is the flow of control in a 'for' loop −
·     The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
·      Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop.
·  After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
·     The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates.
Example 1:
<?php
for ($xint=0; $xint<=5; $xint++)
{
echo "Number is : $xint <br />";
}
?>
Output:

Example 2:
.
<?php
for ($xint = 1; ; $xint++) {
if ($i >= 5) {
break;
}
echo $xint;
}
?>
Output:

Example 3:
<?php
$xint = 1;
for (; ; )
{
if ($xint >= 5)
{
break;
}
echo $xint;
$xint++;
}
?>
Output:

2.FOREACH LOOP:
Foreach and for loop are mostly performs the same except when you're looping over an array where each member has an index. at that point the for loop performs better.
PHP 4 introduced "foreach" construct, it works only on arrays. The foreach looping is the best way to access each key/value pair from an array.
Foreach loop iterates over collections. Many of these collections are implemented as linked list. 
Advantages of foreach loop:
But there are still other advantages using foreach loop than micro-optimisations.
·         Using a foreach loop demonstrates to anyone using your code that you are planning to do something to each member of a collection.
·         It also shows you aren't modifying the original collection (and throws an exception if you try to).
·         foreach is that it works on any IEnumerable, where as for only makes sense for IList, where each element actually has an index.
  • At some stage it might be easier to adapt code using foreach to run on multiple cores.
  • It increases the abstraction level - instead of  having to express the low-level details of how to loop around a list or  array (with an index or iterator), the developer simply states that they  want to loop and the language takes care of the rest.
·         This aids readability and clarity.
Syntax:
foreach (array_expr as $value)
{
statement
}
array_expr is an array. In every loop the value of the current element of the array is assigned to $value and the internal array pointer is advanced by one and the process continue to reach the last array element.
OR
foreach (array_expr as $key => $value)
{
statement
}
array_expr is an array. In every loop the current element's key is assigned to $value and the internal array pointer is advanced by one and the process continue to reach the last array element.

Flow chart of Foreach loop:
Example:
<?php

$fruits_list = array("apple","banana","Mango","Orange","Grapes");

foreach($fruits _list as $array_values){

echo $array_values . "<br>";

}

?>
Output:

Foreach loop using an associative array :
Another example that loops through an associative array.
An associative array uses alphanumeric words for access keys.
Example2:
<?php

$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");

foreach($persons as $key => $value){

echo "$key is $value"."<br>";

}

?>
Output:

 Here the names have been used as array keys and gender as the values. Here the operator “=>” represents the relationship between a key and value.Ypu can imagine that the key points => to the value.
3.WHILE LOOP:
The while statement is simple, it executes the statement(s) repeatedly as long as the condition is true. The condition is checked every time at the beginning of the loop.
They are used to execute a block of code a repeatedly until the set condition gets satisfied
When to use while loops
  • While loops are used to execute a block of code until a certain condition becomes true.
  • You can use a while loop to read records returned from a database query.
Example: Suppose you want to calculate gross salaries of 20 different persons or take a list of maximum and minimum temperatures of a certain month or a year, the while loop is ideal to solve these types of cases.
Types of while loops
  • Do… while - executes the block of code at least once before evaluating the condition
  • While… - checks the condition first. If it evaluates to true, the block of code is executed as long as the condition is true. If it evaluates to false, the execution of the while loop is terminated.
Syntax of While loop:
<?php
While(condition){
Statements to be executed;
}
?>
Here
  • “while(…){…}” is the while loop block code
  • “condition” is the condition to be evaluated by the while loop
  • “statements…” is the code to be executed if the condition gets satisfied

How it works(Data Flow)
The flow chart shown below illustrates how the while… loop works.

Example:
<?php

$i = 0;

while ($i < 5){

echo $i + 1 . "<br>";

$i++;

}

?>
Output:

4.DO…WHILE LOOP:
The difference between While… loop and Do… while loop is do… while is executed at-least once before the condition is evaluated.
Do… while loop is executed at least once even if the set condition evaluates to false.
Syntax:
<?php
do{
Statements to be executed;
}
While(condition is true)
?>
HERE,
  • “do{…} while(…)” is the do… while loop block code
  • “condition” is the condition to be evaluated by the while loop
  • “statements…” is the code that is executed at least once by the do… while loop

How it works(Data Flow)
The flow chart shown below illustrates how the while… loop works.

Example:
<?php

$i = 9;

do{

    echo "$i is"." <br>";

}

while($i < 9);

?>
Output: 9






No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template