PHP For LoopPHP for loop can be used to traverse a 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 the 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. See in the syntax given below Syntaxfor(initialization; condition; increment/decrement){ ParametersThe PHP for loop is similar to the java/C/C++ for a loop. The parameters of for loop have the following meanings: initialization - Initialize the loop counter value. The initial value of the for loop is done only once. This parameter is optional. 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. Example<?php Output: 1
2
3
4
5
6
7
8
9
10
ExampleAll three parameters are optional, but semicolon (;) is must pass in for loop. If we don't pass parameters, it will execute infinitely. <?php Output: 1
2
3
4
.
.
.
ExampleBelow is the example of printing numbers from 1 to 9 in four different ways using for loop. <?php Output: 123456789
123456789
123456789
123456789
PHP Nested For LoopWe can use 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). Example <?php Output: 1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
PHP For Each LoopPHP for each loop is used to traverse array elements. Syntax foreach( $array as $var ){ Example <?php Output: Season is: summer
Season is: winter
Season is: spring
Season is: autumn
For more details of foreach loop, click here. |
0 Comments: