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.

Example:

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>';
}
?>

The output of both examples are the same

Browser Output
James
Mark
John
Barry
Bruce
Joe

PHP Loop Type

There are four types of loops in PHP –

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


Quick Notes:

What are the PHP loops?

Like other languages, PHP also has Loops. The 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.

How many loops does PHP have?

There are four types of loops in PHP –

1) while loop
2) for Loop
3) do-while loop
3) foreach loop

Leave a Reply

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