PHP looping statements – PHP tutorial

PHP looping statements – PHP tutorial. PHP looping statements used for execute same code multiple time. Looping statements loop on array and execute code between block, on every iteration block code have array element value to process.

PHP looping statement types

PHP supports following four looping statements.

foreach − loops through a block of code for each element in an array.

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 specified condition is true.

do…while − loops through a block of code once, and then repeats the loop as long as a special condition is true.

We will also discuss about continue and break keywords used to control the loops execution.

PHP
PHP

foreach – PHP looping statements

foreach (array as value) {
   code to be executed;
}

for – PHP looping statements

for (initialization; condition; increment){
   code to be executed;
}

while – PHP looping statements

while (condition) {
   code to be executed;
}

do…while – PHP looping statements

do {
   code to be executed;
}
while (condition);

The break statement

The PHP break keyword is used to terminate the execution of a loop prematurely.

Suppose in code, you want to break loop, when array element value comes stop, you can use break statement.

<?php

foreach( array('start', 'stop', 'last') as $element) {
    if( $element == 'stop' )break;
    
    //process element
}
 
?>

The continue statement

The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.

Suppose in code, you want to ignore code execution for particular element value. you can bypass loop code execute using continue statement.

<?php

foreach( array('start', 'pass me', 'last') as $element) {
    if( $element == 'pass me' )continue;
    
    //process element
}
 
?>