What are loops in PHP

Like other languages, PHP has loops. So what are Loops?

What are loops in PHP?

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.


1) Without using Loop – Echo all array values.

$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

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

foreach($names as $single_name){
    echo $single_name.'<br>';

The output of both examples are the same

Browser Output

PHP Loop Type

There are four types of loops in PHP –

  1. for loop
  2. while loop
  3. do-while 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.

In the next tutorial, you will learn PHP While Loop.

Leave a Reply

Your email address will not be published. Required fields are marked *