Loops are used to execute the same block of code again and again, as long as a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save the time and effort. PHP supports four different types of loops.
For loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code for certain number of times.
The parameters of for loop have following meanings:
It is used to initialize the counter variables, and evaluated once unconditionally before the first execution of the body of the loop.
In the beginning of each iteration, condition is evaluated. If it evaluates to true, the loop continues and the nested statements are executed. If it evaluates to false, the execution of the loop ends.
It updates the loop counter with a new value. It is evaluate at the end of each iteration.
The foreach loop in PHP is a control structure that allows you to iterate over arrays and objects in a simple and straightforward manner. It is particularly useful for traversing associative arrays and objects where you need access to both keys and values.