Looping Statements in PHP

View: 544    Dowload: 0   Comment: 0   Post by: hanhga  
Author: none   Category: Forum PHPBB, VBB   Fields: Other

9 point/5 review File has been tested

The While statement executes a block of code if and as long as a specified condition evaluates to true. If the condition becomes false, the statements within the loop stop executing and control passes to the statement following the loop.

Introduction

The While Loop :

The While statement executes a block of code if and as long as a specified condition evaluates to true. If the condition becomes false, the statements within the loop stop executing and control passes to the statement following the loop. The While loop syntax is as follows:

while (condition) 
{
  code to be executed;
}

The block of code associated with the While statement is always enclosed within the { opening and } closing brace symbols to tell PHP clearly which lines of code should be looped through.

While loops are most often used to increment a list where there is no known limit to the number of iterations of the loop. For example:

while (there are still rows to read from a database) 
{
   read in a row;
   move to the next row;
}

Let's have a look at the examples. The first example defines a loop that starts with i=0. The loop will continue to run as long as the variable i is less than, or equal to 10. i will increase by 1 each time the loop runs:

<?php
$i=0;
while ($i <= 10) { // Output values from 0 to 10
   echo "The number is ".$i."<br />";
   $i++;
}
?>

Now let's consider a more useful example which creates drop-down lists of days, months and years. You can use this code for registration form, for example.

<?php

$month_array = array( "January", "February", "March", "April", "May", "June",
                      "July", "August", "September", "October", "November", "December");

echo "<select name=\"day\">";
$i = 1;
while ( $i <= 31 ) {
   echo "<option value=".$i.">".$i."</option>";
   $i++;
}
echo "</select>";

echo "<select name=\"month\">";
$i = 0;
while ( $i <= 11 ) {
   echo "<option value=".$i.">".$month_array[$i]."</option>";    
   $i++;
}
echo "</select>";

echo "<select name=\"year\">";
$i = 1900;
while ( $i <= 2007 ) {    
   echo "<option value=".$i.">".$i."</option>";    
   $i++;
}
echo "</select>";

?>

Note: Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate

The Do...While Loop :

The Do...While statements are similar to While statements, except that the condition is tested at the end of each iteration, rather than at the beginning. This means that the Do...While loop is guaranteed to run at least once. The Do...While loop syntax is as follows:

do 
{
   code to be exected;
}
while (condition);

The example below will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than or equal to 10:

<?php 
$i = 0;
do {
   echo "The number is ".$i."<br/>";
   $i++;
} 
while ($i <= 10);
?>

The For Loop :

The For statement loop is used when you know how many times you want to execute a statement or a list of statements. For this reason, the For loop is known as a definite loop. The syntax of For loops is a bit more complex, though for loops are often more convenient than While loops. The For loop syntax is as follows: 

for (initialization; condition; increment) 
{
   code to be executed;
}

Have a look at the very simple example that prints out numbers from 0 to 10:

<?php
for ($i=0; $i <= 10; $i++) 
{
   echo "The number is ".$i."<br />";
}
?>

Next example generates a multiplication table 2 through 9. Outer loop is responsible for generating a list of dividends, and inner loop will be responsible for generating lists of dividers for each individual number:

<?php
echo "<h1>Multiplication table</h1>";
echo "<table border=2 width=50%"; 

for ($i = 1; $i <= 9; $i++ ) {   //this is the outer loop
  echo "<tr>";
  echo "<td>".$i."</td>";
  
   for ( $j = 2; $j <= 9; $j++ ) { // inner loop
        echo "<td>".$i * $j."</td>";
    }

   echo "</tr>";
} 

echo "</table>"; 
?>

At last let's consider the example that uses 2 variables. One to add all the numbers from 1 to 10. The other to add only the even numbers.

<?php
$total = 0;
$even = 0;

for ( $x = 1, $y = 1; $x <= 10; $x++, $y++ ) {
  if ( ( $y % 2 ) == 0 ) {
    $even = $even + $y;
  }
  $total = $total + $x;
}

echo "The total sum: ".$total."<br />";
echo "The sum of even values: ".$even;

?>

The Foreach Loop :

The Foreach loop is a variation of the For loop and allows you to iterate over elements in an array. There are two different versions of the Foreach loop. The Foreach loop syntaxes are as follows

foreach (array as value)
{
   code to be executed;
}
    
foreach (array as key => value)
{
   code to be executed;
}

The example below demonstrates the Foreach loop that will print the values of the given array:

<?php
$email = array('john.smith@example.com', 'alex@example.com');
foreach ($email as $value) {
   echo "Processing ".$value."<br />";
}
?>

PHP executes the body of the loop once for each element of $email in turn, with $value set to the current element. Elements are processed by their internal order. Looping continues until the Foreach loop reaches the last element or upper bound of the given array.

An alternative form of Foreach loop gives you access to the current key:

<?php
$person = array('name' => 'Andrew', 'age' => 21, 'address' => '77, Lincoln st.');
foreach ($person as $key => $value) {
   echo $key." is ".$value."<br />";
}
?>

In this case, the key for each element is placed in $key and the corresponding value is placed in $value.

The Foreach construct does not operate on the array itself, but rather on a copy of it. During each loop, the value of the variable $value can be manipulated but the original value of the array remains the same.

Break and Continue Statements :

Sometimes you may want to let the loops start without any condition, and allow the statements inside the brackets to decide when to exit the loop. There are two special statements that can be used inside loops: Break and Continue.

The Break statement terminates the current While or For loop and continues executing the code that follows after the loop (if any). Optionally, you can put a number after the Break keyword indicating how many levels of loop structures to break out of. In this way, a statement buried deep in nested loops can break out of the outermost loop.

Examples below show how to use the Break statement:

<?php
echo "<p><b>Example of using the Break statement:</b></p>";

for ($i=0; $i<=10; $i++) { 
   if ($i==3){break;} 
   echo "The number is ".$i;
   echo "<br />"; 
}

echo "<p><b>One more example of using the Break statement:</b><p>";

$i = 0;
$j = 0;

while ($i < 10) {
  while ($j < 10) {
    if ($j == 5) {break 2;} // breaks out of two while loops
    $j++;
  }
  $i++;
}

echo "The first number is ".$i."<br />";
echo "The second number is ".$j."<br />";
?>

The Continue statement terminates execution of the block of statements in a While or For loop and continues execution of the loop with the next iteration:

<?php
echo "<p><b>Example of using the Continue statement:</b><p>";

for ($i=0; $i<=10; $i++) { 
   if (i==3){continue;} 
   echo "The number is ".$i; 
   echo "<br />"; 
} 
?>

 

Looping Statements in PHP

Looping Statements in PHP Posted on 16-12-2015  The While statement executes a block of code if and as long as a specified condition evaluates to true. If the condition becomes false, the statements within the loop stop executing and control passes to the statement following the loop. 1.8/10 544

Comment:

To comment you must be logged in members.

Files with category

  • Input Validation Using Filter Functions with php

    View: 463    Download: 0   Comment: 0   Author: none  

    Input Validation Using Filter Functions with php

    Category: Forum PHPBB, VBB
    Fields: Other

    2.25/2 review
    Filter functions in PHP might not be sexy, but they can improve the stability, security, and even maintainability of your code if you learn how to use them correctly.

  • The Open/Closed Principle in PHP

    View: 343    Download: 0   Comment: 0   Author: none  

    The Open/Closed Principle in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    0/2 review
    As usual, a good way to grasp what’s actually behind the curtain of the principle and how to take advantage of its benefits is by example. In this article I’ll be setting up a few approachable ones in an attempt to unveil the principle’s driving...

  • Dependency Injection with Pimple in PHP

    View: 390    Download: 0   Comment: 0   Author: none  

    Dependency Injection with Pimple in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    1.6666666666667/3 review
    In application development, we try to create independent modules so that we can reuse code in future projects. But, it’s difficult to create completely independent modules which provide useful functionality; their dependencies can cause maintenance...

  • Working with Directories in PHP

    View: 527    Download: 0   Comment: 0   Author: none  

    Working with Directories in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    2.25/2 review
    Let's start with simple listing the contents of a directory. We need three functions to perform this task: opendir(), readdir() and closedir(). The opendir() function takes one parameter, which is the directory we want to read, and returns a...

  • Guide to Email (Text / HTML / Attachments) in PHP

    View: 503    Download: 0   Comment: 0   Author: none  

    Guide to Email (Text / HTML / Attachments) in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    0/2 review
    At first let's consider how to send a simple text email messages. PHP includes the mail() function for sending email, which takes three basic and two optional parameters.

  • Dynamic Image Generation in PHP

    View: 417    Download: 0   Comment: 0   Author: none  

    Dynamic Image Generation in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    0/1 review
    At first, have a look at the following script that creates captcha image. Next, we will consider each step of image generation in details.

  • Form Processing with PHP

    View: 730    Download: 0   Comment: 0   Author: none  

    Form Processing with PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    2.6666666666667/3 review
    Before you can process the information, you need to create an HTML form that will send information to your PHP script. There are two methods for sending data: POST and GET. These two types of sending information are defined in your HTML form...

  • Function in PHP

    View: 606    Download: 0   Comment: 0   Author: none  

    Function in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    2.5/2 review
    A function is a block of code which can be called from any point in a script after it has been declared. It is basically a compartmentalized PHP script designed to accomplish a single task. Furthermore, code contained within functions is ignored...

 

File suggestion for you

File top downloads

logo codetitle
Codetitle.com - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.com Develope by Vinagon .Ltd