• Tutorial List

PHP Loops

Last updated Mar 24, 2020

What are loops in PHP?

Like other languages, PHP has loops. PHP loops are used to execute a statement or a block of statements multiple times according to a specific condition.


Why do you use loops?

Loops are helped the user save the effort of writing the same code multiple times, and it also saves the time of the user.

The following two examples have the same output.

1) Without using Loop – Echo all array values.

<?php
  $names = array('James','Mark','John','Barry','Bruce','Joe');

  echo $names[0].'<br>';
  echo $names[1].'<br>';
  echo $names[2].'<br>';
  echo $names[3].'<br>';
  echo $names[4].'<br>';
  echo $names[5].'<br>';
?>

2) Using Loop – Echo all array values

<?php
  $names = array('James','Mark','John','Barry','Bruce','Joe');

  foreach($names as $single_name){
      echo $single_name.'<br>';
  }
?>
Browser Output
James
Mark
John
Barry
Bruce
Joe

Types of PHP Loops

There are four types of loops in PHP –

  1. while loop
  2. do-while loop
  3. for Loop
  4. foreach loop

📝 When you use loops (not only in PHP) you need to be more careful. Because, if the condition of your loop will wrong, then it can crash your server or application.