[php home]

Php_8: Arrays

Arrays are variables that can hold multiple pieces of information. Arrays are a series of key - value pairs:

KEY VALUE
0 south salem high school
1 sprague high school
2 north high school
3 mckay high school
4 mcnary high school
5 west high school


This array would look like this in PHP: Notice that the variable "$salem_keizer" remains the same throughout the array and that the value (the school's name) changes based on the [key]. The key can be either a number, as in this example, or letters. We could use [sshs] as the key for south salem high school. For now, we will focus on using a number as the key.

<?php
$salem_keizer[0] = "south salem high school";
$salem_keizer[1] = "sprague high school";
$salem_keizer[2] = "north high school";
$salem_keizer[3] = "mckay high school";
$salem_keizer[4] = "mcnary high school";
$salem_keizer[5] = "west high school";

// We could then return a single line by using an echo statement:

echo "$salem_keizer[0]";

// this would return "south salem high school"

echo "<p>";

// We can also return the entire array by using a loop

$i=0;
while ($i <= 6) {
echo "$salem_keizer[$i] <br>";
$i++;
}
?>

Creating an array:

There are a couple of ways that you can create an array. Hand coding the array in PHP as in the above example is the first. You can also use the array() function to build an array.

$array = array('value', 'value2', 'value3');
or
$salem_keizer = array ('south ', 'sprague', 'north', 'mcnary', 'mckay', 'west');

If you do not specify a key, the first value will take "0" as a key. You could however, specify a key:

$salem_keizer = array ( 1 => 'south ', 'sprague', 'north', 'mcnary', 'mckay', 'west');

In this example, south will have the key of 1 and Sprague will have 2 and so on.

You can also use this method to create an array of sequential numbers:

$number = range (1, 10);

Exercise 8.1: Create an array of your 6 favorite cars. Use a while loop to display your list.

Examples: PHP Arrays Distance Finder | Wordfind Generator