Shiphp The PHP Developer's Guide

Introduction to Loops in PHP

In programming, we use loops to iterate over data. This can be useful for transforming individual elements in an array, validating input data, sorting, and many other things. PHP offers several methods for looping over data arrays.

“for” Loops

The for loop offers space for up to three parameters: the initial value, the condition, and the increment. In practice, this means that you can do things like counting very easily using for loops. The code:

$i = 0;

for($i; $i < 4; $i++) {
   echo $i . PHP_EOL;

Will output this when run in the command line:


What’s happening is that before PHP executes the block of code within the for(...) { } brackets, it’s checking if the conditional is true, then executing the code, then applying the iterative function ($i++ in this case). That way, the next time PHP executes the block, it’s checking if $i < 4 and it won’t run indefinitely.

Be careful though. You can easily write an infinite loop by omitting that last parameter, and it might cause your computer to run out of memory and crash.

“foreach” Loops

If you want to iterate over an array (ie: take each element in the array and do an operation on it), then a foreach loop might be your best bet.

$array = ['a', 'b', 'c', 'd'];

foreach($array as $key => $value) {
  echo $value . PHP_EOL;

The code above will output a b c d (with each character on a new line) when run in a command line terminal.

“while” Loops

The while loop is similar to PHP’s for loop, but instead of taking three arguments, it just takes one: a condition.

The while loop will test that condition and as long as it is true, it will execute code within the loop. For example, this code:

$j = 0;

while($j < 4) {
  echo $j . PHP_EOL;

Will output the same thing as the for loop example above (0 1 2 3), but it allows you to put the iteration function anywhere within (or even outside) this block of code.

“do…while” Loops

Finally, do...while loops are just like while loops with the conditional check moved to the end of the block. This can be useful if you always want to execute a block once, but you’re not certain you’ll want it to run again.

A simple example would be the following code:

$j = 0;

do {
  echo $j . PHP_EOL;
} while ($j < 4);

Which will output the same thing as our for and while examples above (0 1 2 3).

Like this Post?

Learn to build your first Dockerized PHP application.

In this book, PHP developers will learn everything they need to know to start building their applications on Docker, including:

  • Installing dependencies using Composer.
  • Getting data from a third-party API.
  • Saving data to a MySQL database.
  • Using a web framework (SlimPHP) for routing.
  • Storing environmental variables securely.
  • And much more!

You can buy this book on Leanpub today.

Buy it Now!