May 11, 2021 PHP
Loop the block of code a specified number of times, or when the specified condition is true.
The for loop is used when you know in advance how many times the script needs to run.
Parameters:
Note: The initial value and increment parameter above can be empty or have multiple expressions separated by commas.
The following example defines a loop with an initial value of i-1. T he loop continues to run as long as the variable i is less than or equal to 5. Each time the loop runs, the variable i increments by 1:
Output:
The foreach loop is used to traverse an array, looping blocks of code based on each element in the array.
Each time you loop, the value of the current array element is assigned to the $value variable (the array pointer moves one by one), and on the next loop, you will see the next value in the array.
The following example demonstrates a loop that outputs the value of a given array:
Output:
Note: foreach can only be applied to arrays and objects, and if you try to apply variables to other data types, or if you do not initialize variables, an error message is issued.