PHP iterative constructs

while

$i = 0;
while($i < 10) {
  echo $i.PHP_EOL; // 0 1 ...... 8 9
  $i++;
}
 
$i = 10;
do {
  echo $i.PHP_EOL; // 10 because in a do while loop the code will be executed a least once
  $i++;            // even if the condition never true
} while($i < 10);

for

for($i = 0;$i < 10; $i++) {
  echo $i.PHP_EOL; // 0 1 ...... 8 9
}
 
for($i = 0, $j = 10;$i < 10, $j > 0 ; $i++, $j--) {
  echo $i.' '.$j.', '.PHP_EOL; // 0 10, ... 4 6, ... ,9 1
}

break/continue

$i = 0;
while($i < 10) {
  if($i == 5) {
    break;
  }
  echo $i.PHP_EOL; // 0 1 2 3 4
  $i++;
}
 
$i = 0;
while($i < 10) {
  for($j = 0; $j < 10; $j++) {
    if($j + $i == 15) {
      echo $j.' + '.$i; // 9 + 6
      break 2; // exit from this loop and the next one
    }
  }
  echo $i.PHP_EOL; // 0 1 2 3 4 5
  $i++;
}
 
for($i = 0;$i < 10; $i++) {
  if($i > 3 && $i < 7) {
    continue;
  }
  echo $i.PHP_EOL; // 0 1 2 3 7 8 9
}

Comments are closed.