PHP Arrays



index
Disabled back button Next Section
printable version

Section 0: Module Objectives or Competencies
Course Objective or Competency
The student will be able to write basic PHP applications in order to connect to and manipulate a database using PHP.
Section 1: Example 1

An array can be thought of as a special kind of variable that contains multiple values.

The simplest way to create an array in PHP is to use the built-in array function:

$rates = array(); // creates an empty array
$setRates = array(0.0475, 0.575, 0.700); // creates an array with values
$mixedArray = array(1, 'two', '3');

Just like an ordinary variable, each space in an array can contain any type of value.

The second and third examples show how to initialize an array when you declare it.

You can set or change values an array in the usual way:

$rates[0] = 5.95; // sets the first element

You can add elements to the end of an array by using the assignment operator as usual, but omitting the index value.

$rates[] = 6.95; // sets the second element

Section 2: Associative Arrays

Numbers are the most common choice for array indices, but you can also use strings as indices to create what is called an associative array.

This type of array is called associative because it associates values with meaningful indices.

$salaries['Anderson'] = 75000;
$salaries['Andrews'] = 77500;

The array function also lets you create associative arrays, if you prefer that method.

$salaries = array('Anderson' => 75000,
'Andrews' => 77500);

Here is a link about associative arrays that might be useful.