To execute the same block of code many times the loops are used. PHP supports four types of loops.
- For loop - the code is looped for a specified number of times. It is used when you are aware of how many times you want to execute a statement or a block of statements.
Syntax-
for (initialization; condition; increment){
code to be executed;
}
To set the start value for the counter of several loop iterations initializer is used.
- While loop - the code is looped as long as a specific condition is true. If the condition is true it will be executed. After the execution of the code, it is again evaluated and the loop will continue until the condition is found false.
Syntax –
while (condition) {
code to be executed;
}
- Do…..while loop – the code is looped once and then repeats the loop till the special condition is true.
Syntax - do {
code to be executed;
}
while (condition);
- Foreach loop – the code is looped for each element in an array. In this loop in each pass, the current element array is assigned a $value and the array pointer is moved by one, and when the next pass occurs the next element will be processed.
Syntax - foreach (array as value) {
code to be executed;
The break statement – is situated inside the statement block. You get full control whenever you want to exit from the loop you can come out of it. As soon as you come out of the loop immediate statement to the loop will be executed. The keyword break is used to terminate the execution of the loop prematurely.
The continue statement- like the break statement the continue statement is also situated inside the statement block containing the code which is executed by the loop and preceded by the conditional test. For the pass encountering continue statement rest code of the loop is skipped and the next pass starts.