Back to DFS's Workshop Page
Back to Agenda Page


Arrays I: Traditional One-Dimensional

Quick Links

It is possible to use variable identifiers which are related visually, e.g. $score1, $score2, ... $score100. However, the code to find the highest score out of even five variables that are named in this fashion is both repetitive and long.

$high_score = $score1;
if ( $score2 > $high_score )
  $high_score = $score2;
if ( $score3 > $high_score )
  $high_score = $score3;
if ( $score4 > $high_score )
  $high_score = $score4;
if ( $score5 > $high_score )
  $high_score = $score5;

It would become absolutely unbearable to write and read code which would repeatedly access these variables for various purposes, such as finding the lowest, the average, the median, the mode, or reading the values from the keyboard, or printing them out on the screen.

High-level computer languages, such as Pascal and C, solve this problem by using a data type called an array. In these languages, this data type allows you to use a single identifier for a whole set of values of the same type, e.g., all integers or all chars. (PHP does not restrict an array to containing elements of just a single data type.)

Back to Top

Initializing an Array

In most computer languages, it is necessary to specify how many values will be stored in the array. In PHP, however, arrays are manipulated dynamically. The following pieces of code will all result in an array called $scores with the subscripts and values as specified in this table.

Value5674529088
Subscript01234
Component
Name
$scores[0]$scores[1]scores[2]$scores[3]$scores[4]
  1. This technique explicitly specifies each element by subscript.

    $scores[0] = 56;
    $scores[1] = 74;
    $scores[2] = 52;
    $scores[3] = 90;
    $scores[4] = 88;
    
  2. In PHP, as in C, the default lowest numbered subscript is zero (0). Thus, calling the array() function with a comma-separated list of arguments results in the same data storage.

    $scores = array(56, 74, 52, 90, 88);
    
  3. This third method utilizes defaults in two ways. If a variable has not yet been treated as an array and assigned a value, the first value assigned with no explicit specification of a subscript will be placed in the zeroth element. Each successive assignment with no subscript will result in the current subscript being incremented by 1.

    $scores[] = 56;
    $scores[] = 74;
    $scores[] = 52;
    $scores[] = 90;
    $scores[] = 88;
    

This last technique is very useful when reading values from a file, e.g.

while ( !feof($fp) ) {
   $lines[] = fgets( $fp, 500);
}
will read the entire contents of a file into an array called $lines.

Or it could be used to populate an array with random values. E.g.,

for( $i = 1; $i <= 100; $i++)
   $nums[] = rand(1, 6);
will place 100 values in the range 1 to 6 (such as rolls of a die) into an array called $nums, the subscripts of which will run from 0 to 99.

Back to Top

Using an Array

Among the basic operations done with arrays are finding the largest, the smallest, the average, etc.

Only in the first method of initializing an array which was demonstrated above were the actual subscripts explicitly specified. Unless we want to spend our time counting (in these cases, it is not too bad) how many elements we initialized, we need the system to help us out -- count(), a built-in function, does this.

count() returns the number of elements in the argument passed to it.

If we know that a score cannot be negative, the following code will find the highest score.

$highest = 0;
for( $i = 0; $i < count($scores); $i++)
   if( $scores[$i] > $highest )
      $highest = $scores[$i];

On the other hand, we can let PHP scan through the array without using any subscript at all. Thus, the following code using the foreach keyword and the count() function can be used to calculate the average of the elements in the array without even having a variable holding the number of elements.

$total = 0;
foreach ( $scores as $score )
   $total += $score;
$average = $total / count($scores);

Back to Top

Checking Values in an Array

PHP provides an easy way of checking the values currently in an array. To print out the values held in the $scores array to your web page, use the following code:

echo "<pre>\n";
print_r($scores);
echo "</pre>\n";

The following PHP code can be placed in a file, e.g. dicerolls.php, as a quick KISS test which fills and prints out a $rolls array with ten random values in the range 1 to 6.

<?php
for( $i = 0; $i < 10; $i++)
   $rolls[] = rand(1, 6);
echo "<pre>\n";
print_r($rolls);
echo "</pre>\n";
?>

© 2002-2004 DFStermole
Created: 28 Oct 02
Last Modified: 2 May 04