Creating a Loop in PHP

In PHP, wouldn’t it be useful to be able to simply ‘loop’ through data to cut down on repetition. Of course this functionality already exists and is central to so many things that you can do with versatile language.

Looping with Arrays

An array is a string of data containing multiple parts:

$my_array = array(‘Matthew’, ‘Mark’, ‘Luke’, ‘John’);

You can echo out a single item from this array with the following:

  • Matthew
  • Mark
  • Luke
  • John

Looping with While Loop

The While loop is a little more complex, but is useful especially when aligning and passing multiple arrays. Here is a very simple example:

$i = 1;

while($i <= 5)
echo “Number $i<br>”;

The value of ‘$i’ increases by 1 ($i++) each for each loop. This is echo out:

Number 1
Number 2
Number 3
Number 4
Number 5

Now, let’s apply this to two arrays:

$Names = array(‘John’, ‘Sarah’, ‘Jane’, ‘Pete’);
$Ages = array(28, 27, 32, 23);

echo “My Friends:

$i = 0;
while ($i <= count($Names)-1)
echo “<li>” . $Names[$i] . ” is “. $Ages[$i] . ” old.”;

echo “<ul>”;

This increasing value of $i is place is used to reference a particular part of that array.

Loops have many other uses. You will discover, in later tutorials, that loops can be a fundamental component in displaying multiple lines of information from a database.