Loop in PHP are used to execute the same block of code a specified number of times.
PHP supports following four loop types
for:
loops through a block of code a specified number of times.while:
loops through a block of code if and as long as a specigied condition is true.do...while:
loops through a block of code once, and then repeats the loops as long as a special condition is true.foreach:
loops through a block of code for each element in an array.The for loop statement take three expressions inside its parenthesis. Separated by semi-colons.
The initialization expression is executed. This expression usually initializes one or more loop counter, but the syntax allows an expression of any degree of complexity.
The Condition expression is evaluated. If the value of condition is true, the loop statement execute. If the value of condition is false, the for loop terminates.
The update expression increment executes.
The Number is 0 The Number is 1 The Number is 2 The Number is 3 The Number is 4 The Number is 5 The Number is 6 The Number is 7 The Number is 8 The Number is 9 The Number is 10
The while statement will execute a block of code as long as test expression is true.
If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.
Loop stopped at i =1 and num = 40
The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.
The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.
The number is: 1 The number is: 2 The number is: 3 The number is: 4 The number is: 5
The for each statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.
Value is 11 Value is 12 Value is 13 Value is 14 Value is 15