PHP 101: Loops

Stephanie De Smedt
3 min readApr 23, 2022
Photo by Priscilla Du Preez on Unsplash

The aim of every Web Developer should be to write clean and efficient code. In situations where we need to execute the same task multiple times it would not be efficient to repeat the instructions — for example imagine wanting to print every entry in an array of names to the terminal manually, that could take some time.

Thankfully, PHP gives us the option to write loops which take care of this exact problem.

Loops

Loops state that a block of code should be executed multiple times while certain conditions are valid. This post will cover 4 different types of loop and how to properly construct them.

1. while

A while loop will continue to be executed whilst a specified condition is true. For example, if we wanted to print the numbers from 1 to 5 to the terminal we could setup a while loop like the one below:

$count = 1;
while ($count <= 5) {
echo $count;
$count += 1;
}
//This will return 12345

It is important to remember to iterate the variable (in the example above this is achieved by adding 1 to count) otherwise the code will get stuck in an infinite loop.

2. do… while

The “do…while” loop is very similar to while, however, the loop will execute at least once before a condition is…

--

--

Stephanie De Smedt

Project Manager learning Web and Mobile Development. A lifelong learner with a travel and coffee problem.