Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 4.3Loops in PHP

Part 4.3Loops in PHP

The next part of the tutorial will cover loops.

A loop is designed to repeat (or loop) a command permanently or until it meets a condition. A loop which awaits a number to meet a certain point and looks through a list (array) is known to be iterating through the list.

There are two types of loops covered in this tutorial, namely Do and For. Both have specific purposes and are fundamentally different, but can both be used to perform the same thing.

For loops

A for loop can be one of two kinds which can be separated into:

  • For X to Y
  • For Each

Both are very different and have uses where one is better than the other. Knowing when to use each is an important part of web programming, and so additional reading into the project may be necessary in order to understand which loop works better.

In the following example, the PHP script will get a list of directories in the current directory using the glob function and it will iterate through the list and output the directory and a link to the directory.

PHP
<?php
    //Simple PHP script to get all directories and output links to them
    $files = glob($baseString . '/*', GLOB_ONLYDIR);
    foreach($files as $file)
    {
        echo '<a href="'.$file.'">File number ' . ++$pos . '</a>';
    }
?>
        

This loop is finding every file in the directory that the page is contained in and then it is iterating through that list to echo out all of the found directories as links.

When working with a standard for statement that works from one number to another we declare an iterator. Normally, in programmers conventions, this is called iiThis is the name for this variable as it refers to the iterator. Programmers have used this for a long, long time. for the simple reason of naming conventions.

PHP
<?php
    //PHP script to demonstrate how standard for statements work
    $max = 10;
    for ($i = 0; $i < $max; $i++)
    {
        echo $i;
    }
?>
        

Do While loops

Another way of performing the above loop is using a while statement. A while statement consists of a similar structure, but it does not specify an iterator. At this point, this looks silly, but it can be a good way of looping until something happens that is less comparable, for instance a password as a string.

In this example, we are going to use a while statement to obtain the number from 1 to 10.

PHP
<?php
    //Simple PHP script to count to ten
    $max = 10;
    $pos = 0;
    while ($pos < $max)
    {
        //Pre incrementation
        echo ++$pos;
    }
?>
        

And that is conditional statements in PHP.

Feedback 👍
Comments are sent via email to me.