Sometimes we want a program to repeat something over and over again. A loop is used to make a program do something more than one time. In this tutorial, you will learn what are loops in PHP and why they are important.
The loop is used to re-execute a block of code until the specified condition is met. Sometimes loops are beneficial for developers to save the time and effort of writing similar code.
Here are two PHP code snippets below that display the same output. One has manual code written in it, and the other uses loops. With this example, you can understand why the loop is so important.
Without Using Loop
Example:
<?php
$names = array('Alex','Peter','Mark');
echo $names[0].'<br>';
echo $names[1].'<br>';
echo $names[2].'<br>';
?>
Using loop
Example:
<?php
$names = array('Alex','Peter','Mark');
foreach($names as $name){
echo $name.'<br>';
}
?>
PHP supports the following types of loops:
All are slightly different and provide loops for different situations. They are explained in further lessons.