PHP Guide 2: Loops and Arrays

A guide to using loops in PHP, including the for, foreach and while loops. And learn how to use arrays.

Index of Contents

»The For Loop
»Arrays
»Combining loops and arrays

The For Loop

A loop is a block of code that is ran a certain number of times, or ran for each line or row in a data source. There are two main types of loops in PHP: for and while.

<?php

// Let's say we want to write a sentence to our HTML document 10 times, each time increasing in font size.
// Normally we would just write the sentence 10 times, adjusting the font size each time. But PHP loops makes
// it easier. Take a look at this code:

for($i=1;$i<=10;$i++)
{
      echo '<span style="font-size: ' . ($i + 9) . ';">Hello</span>';
}

// This will output Hello ten times, starting at font size 10 and going to font size 20 (increasing by 1 each time).
// for() is the function we are using here, and notice that it doesn't end with a semi-colon. Instead, if has
// curly brackets which surround the code that is ran. Let's dissect the loop code. The first part is $i=1,
// which means that our $i variable we use in this group will start at 1. The next part, $i<=10, means that when
// our $i variable reaches 10, the loop will end. The third part is $i++, which means that our $i variable will
// increase by 1 every time through the loop. Note that we don't need to use $i for our variable, here is
// another simple loop with the same output as above, using a slightly different approach.

$size = 10;
for($n=1;$n<=10;$n++)
{
      echo '<span style="font-size: ' . $size . ';">Hello</span>';
      $size = $size + 1;
}

// Here we use out own variable, $size, and increase it manually by 1 every time through the loop. Also, our loop
// variable, $n, isn't even used in the code block we are looping through. Of course this second example isn't
// as efficient as the first one, and takes more lines of code.

// I personally use the for loop most often, but the while loop is useful as well:

$size = 10;
while($size<21)
{
      echo '<span style="font-size: ' . $size . ';">Hello</span>';
      $size = $size + 1;
}

// Using "while" may make a little more sense than "for" at first. I suggest practicing with both.

?>

Arrays

Now let's look at arrays. You learned how to use variables in the first guide, and arrays aren't too different. They also store data, but can store multiple data parts in a single variable. For example, say you want to store someone's first and last name in a varable, but keep them separate so you could easily display either one or both together. Using an array this is simple.

<?php

// Arrays are set similar to variables, and they must have a $ proceeding their name. However, the syntax is a
// little different.

$myfirstarray = array('first' => 'john', 'last' => 'smith');

// In this array I have two key/value pairs. They are separated by a comma. We use => to separate the key
// from the value. This will probably seem a little wierd to you at first. Know that the first term is the key
// (represented by first and last in the above array) and the second term is the value (john and smith). You call
// the key of an array to return its value. Here is an example:

echo $myfirstarray['first'];

// The above will print out the value associated with the "first" key of our array, which is john.

echo $myfirstarray['last'] . ', ' . $myfirstarray['first'];

// The above will print out the "last" key, a comma and space, and then the "first" key. Can you see how arrays
// allow us to display related data easily and in different ways?

// If we create an array with only values and no keys, PHP will automatically assign keys on a numeric basis,
// starting at 0.

$thearray = array('somedata', 'moredata', 'evenmore');

// Since we haven't specified keys, PHP has automatically assigned the value "somedata" to the key 0,
// "moredata" to the key 1, and so on. We can retrieve this data like so:

echo $thearray[1];

// The above will output: moredata
// Notice again that I didn't use quotes around the number. I could have with the same result, but since it is
// a number it is better to treat it as such.

?>

Combining loops and arrays

The foreach loop, which we haven't talked about yet, is particularly useful for looping through an array and executing code for each key/value pair.

<?php

// Let's create an array with names that we will want to display in a table. This time we're going to
// cheat a little and assign the first name to the key, and the last name to the value, for each key/value pair.
// This allows us to have lots of people's names in the same array without having to use nested arrays.

$namearray = array('john' => 'smith', 'larry' => 'farmers', 'jane' => 'doe');

// The foreach loop does what it sounds like it does. It executes some code "for each" pair in the array.

foreach($namearray as $firstname => $lastname)
{
      echo $firstname . ' ' . $lastname . '<br>';
}

// For the above loop, we first state the array we are going to loop through, then "as", then we assign a
// variable to the key and value. It is a good idea to make these descriptive. Notice we used => to separate
// the key and value pair.

?>

Next Guide: Working with GET and POST Form data

© Nick Vogt 2012