HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP while Loop


A while loop in PHP is a control flow statement that repeatedly executes a block of code as long as a specified condition remains true. It's a fundamental building block for iterative tasks in your code.

The while loop executes a block of code as long as the specified condition is true.



Example


<!DOCTYPE html>
<html>
<body>

<?php  
$i = 1;

while ($i < 6) {
  echo $i;
  $i++;
} 
?>  

</body>
</html>

Output

12345

The while loop does not run a specific number of times, but checks after each iteration if the condition is still true.

The condition does not have to be a counter, it could be the status of an operation or any condition that evaluates to either true or false.



• The break Statement

With the break statement we can stop the loop even if the condition is still true:


Example


<!DOCTYPE html>
<html>
<body>

12  

</body>
</html>

Output

12

• The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Example


<!DOCTYPE html>
<html>
<body>

<?php  
$i = 0;

while ($i < 6) {
  $i++;
  if ($i == 3) continue;  
  echo $i;
} 
?>  

</body>
</html>

Output

12456

• Alternative Syntax

The while loop syntax can also be written with the endwhile statement like this

Example


<!DOCTYPE html>
<html>
<body>

<?php  
$i = 1;

while ($i < 6):
  echo $i;
  $i++;
endwhile;
?>  

</body>
</html>


Output

12345