• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » PHP » PHP Control structures: Loops
Next →
← Prev

PHP Control structures: Loops

By Dinesh Thakur

This tutorial follows the one on conditional statements. The loops are a trivial principle of computing that any developer must master. They are, too, some of the control structures. PHP 4 into account, each with its specific characteristics: for (), while (), do-while () and foreach ().

We’ll be covering the following topics in this tutorial:

  • What is a loop?
  • The for loop ()
  • The loop while ()
  • The do loop {…} while ()
  • The foreach loop
  • The stop instruction and continuity

What is a loop?

The term “loop” control structure capable of performing a number of times the same set of instructions as a function of one or more conditions to be checked.

It will always check conditions become false (FALSE) at some point in order to get out of the loop. Otherwise, the loop will become infinite and will crash the program until the max_execution_time php.ini will not be achieved.

The for loop ()

This is the most famous loops because it is present in most programming languages. Paradoxically, it is not necessarily the most used PHP programming. What for ? In most programming languages, the for statement () is used to browse a table, whereas PHP has its own control foreach () statement specifically dedicated to this task.

The peculiarity of the loop () (translate “for each iteration”) is that we must know in advance the stop condition. In other words, the value that will make the false condition and will stop the loop. Its syntax is simple and takes three mandatory parameters:

Syntax for () loop

for (initialization; condition; increment)
   {
      instruction block;
   } 

• Initialization is the expression that initializes the loop (starting value). Generally, loops begin at 0.
• The second parameter is the stop condition of the loop. This condition is recalculated at each iteration (feedback loop) to determine if we continue to buckle or if one leaves the loop.
• The last parameter determines the phrase that will be executed at the end of an iteration. Generally it is expected here an increment (or decrement) to update the counter of the loop.

The following example shows the generation of the multiplication table of 9.

Generation number of multiplication table 9 with for ()

<?php
    // Loop generating the multiplication table of 9
    for ($i = 0; $i <= 10; $i ++)
       {
           echo '9 x ', $i, ' = ', (9 * $i) ,'<br />';
       }
?> 

Explanations:

• We initialize our loop to 0. This is the first value that will be multiplied in number 9.
• We stop the loop when the $i counter reaches the value 11. The value 10 but when will i be worth $11 then the program will exit the loop.
• We determine the action to take at the end of each iteration. Here are asked to automatically increment the counter $i in writing $i++ ; (Reminder: $i++ <=> $i = $i+1).
• We display 10 values ​​of the multiplication table of 9. The program calculates each value as the product of $9 by the counter i.

Note: the variable $i is completely arbitrary. This letter is used by convention (for i index) but nothing prevents write $ counter example.

The loop while ()

The while loop () means that we will repeat a block of statements as long as the last setting condition remains true (TRUE). When it becomes false (FALSE), the program will exit the loop.Its syntax shown below:

Syntax of the conditional structure while ()

while (condition)
   {
       instruction block;
    } 

It is used particularly when the extracted information in a database. The peculiarity of this statement is that the condition is tested after the complete execution of the statement block. If the condition becomes false before the end, the remaining instructions will still be executed. Returning to our previous example, but this time with a while () loop.

Generation number of multiplication table 9 with while ()

<?php
   // Declaration and initialization counter
   $i = 0;
   // Loop generating the multiplication table of 9
   while ($i <= 10)
     {
         // Display the new line
         echo ' 9 x ', $i, ' = ', (9 * $i) , '<br />';
        // Increment the counter
        $i ++;
     }
?> 

Explanations:

• Unlike the for () loop, we need to declare and initialize our counter before entering the loop. The default value is the same, ie 0.
• Then we determine the stop condition. When i will be worth $ 11 we will come out of the loop. The conditon $i <= $ 10 is always true as $ i is less than the value 11.
• Finally in the body of the loop, we calculate, and print the product of $ 9 by the counter i before finishing with a counter increment.

The do loop {…} while ()

The statement do {…} while () (translated as “repeat / do … as” an alternative to the while statement () that tests the condition after the first iteration and execution of the first block of . Here are instructions syntax:

Syntax of the control structures do – while ()

do
{
   instruction block;
}
while (condition); 

With our example, this would give:

Generation number of multiplication table 9 with do – while ()

<?php
    // Declaration and initialization counter
    $i = 0;
   // Loop generating the multiplication table of 9
   do
    {
        // Display the new line
       echo '9 x ', $i, ' = ', (9 * $i), '<br />';
       // Increment the counter
       $i ++;
     }
    while ($i <= 10);
?> 

Explanations:

• We begin by initializing the counter to 0.
• Then we define the instruction list to run. Ie, computing, product display and incrementing the counter.
• We conclude with the test provided for out of the loop or not.

Note: If we had initialized the $ i counter to a value strictly greater than 10 (11, 12, 13 …), then the program would have calculated and displayed by the product of this value and 9 would be out of the loop because the condition is false at the beginning.

The foreach loop

In most programming languages, the route table is realized using loops. PHP has in turn its own control structure for browsing the contents of a table. This is the foreach () structure. It is a special loop which advances pointer table each iteration. It has been integrated since version 4 of PHP and comes in two syntaxes:

Syntax foreach control structure ()

<?php
   // Display the values ​​of an array
   foreach ($MyArray as $value)
    {
        echo $value, '<br />';
    }

    // Display the key / value pairs
    foreach ($MyArray as $key => $value)
     {
          echo $key, ‘:’, $value, ‘<br />’;
     }
?>

This structure takes as parameter the name of the table to go and retrieve the data you need (only values ​​or + key values). In the first syntax, the value of the
current element of the array is directly assigned to the variable $ value. In the second, the current key of the array element is assigned to the variable $key
and value stored in the variable $ value.

Note: foreach () works on a copy of the original array.

Consider two tables of example. The numerically indexed and the other associatively. We’ll go through them both with two foreach () statements in a different syntax.

Course tables with foreach ()

<?php
   // Declare the two tables
   $vegetables = array ('salad', 'onion', 'chilli', 'carrot', 'egg');
   $colors = array ('red' => '#ff0000', 'green' => '#00ff00', 'blue' => '#0000ff');

   // Display vegetables
   foreach ($vegetables as $vegetable)
     {
         echo $vegetable, ‘<br />’;
      }

   // Display the colors and their hex code
    foreach ($colors as $color => $codeHexadecimal)
      {
          echo $color, ‘:’, $codeHexadecimal, ‘<br />’;
      }
?>

The stop instruction and continuity

PHP also introduced two special instructions loops. It is a continuous and break. The first is used to force the passage to the next iteration by jumping all or part of the block of instructions to execute. The second, meanwhile, can force out a conditional structure such as for(), while(), foreach() or switch().

These two instructions can take an optional integer parameter to know the number of nested structures that were interrupted.

Briefly illustrate these concepts with simple examples.

Example of continuous use

<?php
   for ($i = 0; $i <= 10; $i ++)
     {
         // It does not display the first 5 numbers
         if ($i <= 5)
            {
                continue;
            }
         // Display the numbers from June to October
              echo $i, '<br />';
       }
?> 

In this example, we want to iterate from the start value 0 but we want to show that values ​​ranging from 6 to 10. With the condition and continues keyword, we can not view the first 6 values.

Note: we could achieve the same result without using the keyword continues by replacing the condition of the if () for $i> 5 and placing the echo () statement instead of continuing.

Easy-to-break

<?php
    for ($i = 0; $i <= 10; $i ++)
       {
           // It displays the counter value
           echo 'Counter = ';
           // We go out of the loop if we reached the figure 5
           if ($i> 5)
              {
                   break;
              }
          // Display the numbers 0-5
          echo $i , '<br />';
      }
?> 

This example illustrates the use of the break keyword. Here we ask to exit the loop as soon as we reached the figure 5. To convince us of the result is the result generated:

Result of the script

Counter = 0
Counter = 1
Counter = 2
Counter = 3
Counter = 4
Counter = 5
Counter =

We note here that we entered the seventh iteration. The program executes the first instruction and then pass the test. The condition is true then the break

You’ll also like:

  1. PHP Control structures: conditions
  2. What is the difference between ‘for’ and ‘while’ loops
  3. Nested Loops in C
  4. Nested FOR Loops in C
  5. Iteration Statements or Loops in C++
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

PHP Tutorials

PHP Tutorials

  • PHP - Home
  • PHP - Features
  • PHP - Magic Methods
  • PHP - Imagefilter
  • PHP - Arrays Numeric
  • PHP - Sessions
  • PHP - Forms Processing
  • PHP - clone()
  • PHP - Cookies
  • PHP - Variable Types
  • PHP - First program
  • PHP - call()
  • PHP - Iterator interface
  • PHP - Imports files
  • PHP - Exception Handling
  • PHP - set() and get()
  • PHP - Install MAMP
  • PHP - Functions
  • PHP - Constants Types
  • PHP - Comments Types
  • PHP - OOP's
  • PHP - OOps Use
  • PHP - PHP Code & Redirect 301
  • PHP - Control structures
  • PHP - Abstract Classes
  • PHP - Control structures
  • PHP - Classes
  • PHP - MySQL NULL values
  • PHP - Methods Visibility
  • PHP - Operator Types
  • PHP - Short tags Not use
  • PHP - Object and class
  • PHP - Secure Passwords

Other Links

  • PHP - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2023. All Rights Reserved.