PHP For Loop

0
6146

We finished studying decision making control statements. Today we will learn one form of looping control statement.

  • What are looping statements?
    • We learned decision making statements that help us to take accurate decisions.
    • But there are some situations where we need to repeat some statements, required number of times.
    • For example: if you are asked to print your name 5 times, you will have to write the echo statement echo “xyz
      ”;
      5 times.
    • This is all right, writing echo statement 5 times is not a big deal.
    • But imagine that you are asked to write your name 1000 times. You will think of leaving the task, the moment you hear it.
    • Here looping statements come into picture.
    • These looping control statements are also called as repetitive statements.
    • Using looping statements we can execute a block of code, specified number of times.
    • In PHP there are 4 looping statements:
      1. For loop
      2. Foreach loop
      3. while loop
      4. do…while loop
    • Among these 4 statements we will study for loop and foreach loop in this tutorial.
  • For loop:
    • For loop is the most widely used looping construct.
    • Syntax of for loop is given below:
    • In the syntax above for is a keyword. Remember that in PHP keywords are not case-sensitive but variables are case-sensitive.
    • The loop is given the information as to from which value to start and where to stop.
    • For loop have 3 parameters in the parenthesis following the keyword for.
      1. Initialization: a counter is required to count the number of loops taking place. This counter is initialized to an initial value to 0 or 1 to start the loop for the first time.
      2. Condition check: a condition is checked to decide whether the loop should be continued or not. If the condition evaluates to true the loop is continued and terminates when the condition evaluates to false.
      3. Increment/decrement: the counter is incremented or decremented as specified.
    • Let us understand deeply how the code in for loop is repeated specified number of times with an example.
    • Create a new folder named for_loop in the htdocs folder inside xampp folder. Then open a new notepad++ document and save it as index.php in the newly created for_loop folder.
    • Write the following code in index.php file.
    • In for loop we have used $i as the counter. It is initialized to zero (0).
    • The initialization, condition check and increment/decrement are separated by semi-colon (;);
    • The initialization statement is executed only once at the beginning of execution of the loop when $i is initialized to zero (0).
    • After initialization of $i to zero, the condition $i<5 is checked. As the value in variable $i (0) is less than 5, the condition evaluates to true.
    • Therefore the control enters the for loop block i.e. inside the curly braces and executes all the statements there. In the above example the statement
      will be executed which will print PHP For Loop.
    • After execution of the statement the control again goes to for statement and increments the counter by 1.
    • Now value of $i is 1 due to increment.
    • Now it checks the condition $i<5 again i.e. 1<5, this again evaluates to true.
    • As it evaluates to true, the echo statement is again executed.
    • In this way the increment, then the condition check and then the statement execution takes place in a cycle till the condition evaluates to true.
    • Once the condition evaluates to false, the loop terminates.
    • As the condition in the above code is $i<5, the loop will repeat 5 times i.e. from 0 to 4. As soon as the value of $i becomes 5, the loop will terminate.
    • Remember the initialization is done only one at the beginning of the loop.
    • The output is shown below:
    • for_loop_output
      fig 1

    • For loop is the only loop with initialization, condition check and increment/decrement together in one single statement.
    • Whatever you want to repeat number of times you can use it in loops.
    • If you initialize the counter variable outside the loop, you can omit it from the for statement.
    • If you have incremented or decremented the counter inside the for loop block, you can even omit it from the for statement.
    • That means you can write the for loop in the above program in the following manner also:
    • We have shown here only the PHP code.
    • The output will be same as shown in figure 1.
    • Remember increment or decrement is very important in any loop, otherwise the counter will never increase or decrease and the condition will never evaluate to false. And the loop will continue infinitely.
    • Also remember that even if you don’t write the initialization and increment/decrement in the for statement, make sure that you give semi-colons in the for loop as specified in the above code. If you forget to give the semi-colons, it will generate a syntax error.
  • Foreach loop:
    • foreach loop is a special loop which can be used only for collections such as arrays.
    • Array is a collection of similar type elements.
    • foreach loop is used to traverse through each key/value pair in an array.
    • Let us have a look on syntax of foreach loop:
    • In the above syntax foreach and as are the keywords.
    • $array_name is the name of that array whose values you want to display.
    • $variable is any variable which is used to fetch one value from array and display it.
    • It need not be incremented like for loop because it is auto-incremented in foreach loop.
    • Let us have an example:
    • We will declare an array of cities and display all its values using foreach loop.
    • Write the following code in index.php file:
    • We will learn deeply about arrays in next chapters, only concentrate on foreach loop now.
    • We have an array named $cities with names of 5 cities.
    • We have displayed all the array values with foreach loop.
    • In the foreach loop $cities is the array name, as is the keyword and $x is any variable used to fetch the value.
    • In this loop first value Delhi from array $cities is fetched by $x and displayed. Then it is auto-incremented and fetches the next value Mumbai and so on till all values in array are fetched.
    • The output is shown below:
    • foreach_loop_output
      fig 2

  • Nested-For loop:
    • We can have nested for loop also, that is one for loop inside another for loop.
    • This is used in situations where we require 2 counters.
    • We know how a for loop executes, it initializes the counter first then it continuously checks the condition, increments or decrements the counter and executes the statements till the condition does not evaluate to false.
    • In nested loop the counter of the outer for loop is initialized first and its condition is checked. If the condition is true, the control enters the outer for loop block, executes the statements if any and then enters the inner for loop.
    • Once the control enters the inner for loop, it executes it completely i.e. till its condition evaluates to false and then again goes to outer for loop to perform its increment or decrement task.
    • Once the increment/decrement is performed, it again checks its condition. If the condition evaluates to true, it again enters the inner for loop and executes it completely.
    • This continuous till the condition of outer for loop does not evaluate to false.
    • Syntax of nested for loop is as follows:
    • Let us see an example.
    • We will try to print a multiplication table of 1 to 5 using nested for loops.
    • Write the following code in index.php file:
    • Here, in the above code we have used nested for loop to display multiplication table of tables from 1 to 5 at a time.
    • Let us understand how it is done.
    • The outer for loop has counter $x and the inner for loop has counter $y.
    • $x is initialized to 1 and the condition used in outer for loop is $x<=5 because we want the loop to continue 5 times, since we want tables from 1 to 5.
    • $y is initialized to 1 and the condition used in inner for loop is $y<=10 because we want the loop to repeat 10 times, since in a multiplication table we multiply 1 to 10 numbers to the number whose table we want to generate.
    • Now let us understand the execution of the above code:
      1. At the beginning in the outer for loop $x is initialized to 1.
      2. Then the condition $x<=5 is checked, it evaluates to true because 1 is less than 5.
      3. Then the control enters the outer for loop block.
      4. It executes the statement
        and prints Tabel of 1:
      5. Next the control moves further and initializes $y in inner for loop to 1.
      6. Then it checks the condition $y<=10, it evaluates to true because 1 is less than 10.
      7. Then it enters the inner for loop block.
      8. Then it executes the statement
        and prints 1 * 1 = 1.
      9. Then the control again returns to the inner for loop statement and increments value of variable $y by 1. Now $y contains value 2.
      10. Then the condition $y<=10 is again checked, it evaluates to true since 2 is less than 10.
      11. The again the statement
        is executed and 1 * 2 = 2 is printed.
      12. The steps from 9 to 12 are repeated 10 times i.e. till the value of $y does not reach 11 where the condition $y<=10 evaluates to false.
      13. Once the condition in inner loop evaluates to false, the control comes out of the inner loop and a line break is printed i.e. a line is left blank.
      14. Then the control reaches the increment statement of outer loop. There it increments the value of $x by 1. So now $x contains value 2. This indicates we are now going to print 2’s table.
      15. Then again condition $x<=5 is checked which evaluates to true. The control enters the outer for loop block and executes the statement and prints Table of 2:
      16. Then the control again enters inner loop and executes its statement 10 times and prints the whole table of 2.
      17. Then again leaves a line break and reaches outer loop’s increment statement.
      18. This thing continues till the outer loop executes 5 times i.e. till the condition $x<=5 does not evaluate to false.
    • In this way the tables from 1 to 5 are printed.
    • The output is shown in multiple figures below:
    • nested_for_loop_output_1
      fig 3

      nested_for_loop_output_2
      fig 4

      nested_for_loop_output_3
      fig 5

      nested_for_loop_output_4
      fig 6

    • From this you can easily understand that the inner loop executes completely when the outer loop has executed only once.
    • With this understanding you can write any program using nested loops wherever required.
    • You can use nesting with any loop.

Thus we finished learning for loop and its various forms in this PHP For Loop tutorial.

LEAVE A REPLY

Please enter your comment!
Please enter your name here