Programming in PHP

4.28 (118)

Looping over Arrays

Loops and arrays go together like two peas in a pod. They are made for each other. An array is an ordinal set of data and a loop will repeat one thing at a time, therefore you can use a loop to iterate over all of your data.

This is an incredibly powerful concept, as it allows you to easily manipulate large chunks of data, when you don't particularly know what the data is. This may be data from a form or from an database, and your script will process it and turn it into an output. To demonstrate looping over arrays we are first going to find the average of a undetermined amount of numbers.

Looping over Arrays
<?php

$numbers 
= array (24.3178366103.22942);
$count count($numbers);
$total 0;

for (
$i 0$i $count$i++) {
    
$total $total $numbers[$i];
}

$mean $total $count;

echo 
'The average is ' $mean;
?>


To explain this script a little, at first we define our array $numbers. It just happens to have six elements. The count function will return the number of elements in the array. Functions will be explained in more detail later on, but basically we write the function name, followed by the data it will process (in this case the array) and we assign it to a variable ($count). This will assign $count to equal six. We then create a for-loop which will start at the first element all the way up to the last element in the array. We then use the for-loop index to get the value of the array at that index. This number is then added to the total, of which after the loop is divided by the number of elements to produce the average.

The important part of this script is the accessing of the array elements within the for-loop. As we have defined the configuration of the for-loop to use $i, we can then access this value of $i inside the for-loop. As this value is increasing by one each time, it is counting. This number can then be used to count through the array to go to the index we want to access. This allows us to use our standard array syntax and get the value at the point of the array where the index equals $i.

Non-Ordinal Arrays


Non-Ordinal arrays are those arrays where we did not specify the index to be like a count. For example, the indexes don't equal 0, 1, 2…n but may be 1, 5, 6, 11. This causes a problem with using a for-loop to loop over the array as for-loops are counting loops. The solution to this problem is to use a new type of loop, designed specifically for arrays.

The foreach-loop is a special loop which will go through each element in an array even if they are not ordinal. Therefore, it can loop efficiently over an array which may have a mix of string and integer indexes. There are two different methods are using a foreach-loop:

foreach ($array_name as $value) {
    statements;
    statements;
}

foreach ($array_name as $index_name => $value) {
    statements;
    statements;
}


The first method is the most common way, but the second is also used if you want to get the name of the index (usually if it is a string). Both methods use the foreach statement with the loop configuration in brackets after it. The statements are once again surrounded within curly braces. You should have now figured out, that when you have a block of code doing a specific function, i.e. loops and conditions, then you surround the block in curly braces.

In the configuration part of the foreach-loop, array_name is simply the variable name that you have given to your array. The $value is the element value in the array. Basically this is the variable name you are going to use within the loop, to access the current value of the array at the index. When using a foreach-loop you may not know the index though, unless you use method two.

In method two, we have the term $index_name => $value. This means that the current value of the index / the index name will be stored in the value called $index_name and the value of the array at this index will equal $value. It is usually easier to understand if we see an example:

Foreach Loop
<?php
$random
[] = 'Howard';
$random[3] = 'Jill';
$random['Friend'] = 'Billy';
$random[6] = 'Jane';

foreach (
$random as $value) {
    echo 
'Value: ' $value "\n";
}

foreach (
$random as $key => $value) {
    echo 
'Key: ' $key ' Value: ' $value "\n";
}
?>


This script will loop over each value in the array twice – once for each foreach-loop. In the first foreach loop, we are only getting the value for each index and then printing it to screen. The \n character simply means a new line (similar to press [ENTER] on the keyboard) to increase readability.

The second foreach-loop is getting the value for both the index name as well as the value at that index. This way, we can find out what we called the index for each element in the array. The output from this script would be:

Value: Howard
Value: Jill
Value: Billy
Value: Jane
Key: 0 Value: Howard
Key: 3 Value: Jill
Key: Friend Value: Billy
Key: 6 Value: Jane


As you can see, for the first four lines (the first loop), only the actual values were printed. For the second loop, the values of the indexes were also printed. Naturally our indexes are not ordinal, and are quite random, hence why we are using a foreach-loop. Foreach-loops can also be used on ordinal arrays and it is quite common to do this, because these loops are so simple to use.

Looping over Multi-Dimensional Arrays


When you have two or more dimension arrays, you have to use more loops to get at your data. As a general rule, you will need one loop for every dimension in your array, in order to get the data. The standard way of doing this is to put a loop within a loop. This means, each time the outside loop does one loop, the inside loop must fully complete it's looping sequence from start to finish:

Loops in Loops
<?php
$people 
= array ( array ('Name' => 'John''Age' => 22'Height' => 174),
        array (
'Name' => 'Paul''Age' => 26'Height' => 182),
        array (
'Name' => 'Jenny''Age' => 40'Height' => 166));

foreach (
$people as $value) {
    foreach (
$value as $key => $data) {
        echo 
$key ': ' $data "\n";
    }
    echo 
"\n";
}
?>


This may at first seem difficult to understand, however, if you break it up into parts it becomes more manageable. First you will notice we have a two dimensional array, as it is an array of arrays. As we have not defined any indexes for our outer array, they will automatically take on ordinal numbers. The inner arrays contain words as indexes to explain what the data they are holding is. This is not a very efficient model of the data, however, is only used to illustrate this principle.

The outer foreach loop is simply going to iterate over each of the elements in the outer array. As the elements are arrays themselves, we can use another foreach-loop to iterate over all of them to get the values. This time however, we specify the $key so that we can get the name of the index. We then print the name of the key and the data, separated by new lines. The output of this script should seem quite obvious now:

Name: John
Age: 22
Height: 174

Name: Paul
Age: 26
Height: 182

Name: Jenny
Age: 40
Height: 166


There is not much more to array creation and looping that has been described here, so onto one of the last important programming concepts; functions.
Rate this article: BAD 1 2 3 4 5   GOOD
<<     Page 8 of 10    >>

Build Your Own Database Driven Website Using PHP & MySQL

  • Installation instructions for Windows, Linux and Mac OS X
  • Instantly apply working code examples from the book to your Website
  • Build a working Content Management System from scratch
  • Master MySQL database administration
  • Fully updated for PHP 5

       Download FREESample Chapters Now!

Ads

PHPNerds Newsletter