PHP Scripts and Resources for Webmasters

PHP Array Tutorial

This tutorial will demonstrate how to use arrays in PHP. An array is simply a collection of keys and their associated values. In PHP, the key can be either an integer or string, while the value can be any PHP data type.

Creating an Array

In PHP, arrays are created using the array() function:

$blankArray = array();

Initializing an Array

An array can be initialized with a set of values by passing the values as parameters to the array() function:

$anArray = array('A', 'B', 'C', 'D');

When initializing an array in the manner above, the values are automatically associated with integer keys in sequential order, starting at zero. The keys can be specified explicitly using the => operator:

$myArray = array('firstKey' => 'A'
	, 'secondKey' => 'B'
	, 19 => 'C'
	, 22 => 'D');

Retrieving Values from an Array

Values can be retrieved from an array using the square bracket syntax below. If the key is a string, it is considered good practice to always use quotes.

echo $myArray['firstKey'];   // A
echo $myArray[19];           // C

Adding Values to an Array

Values can be added to an array using the syntax below:

$myArray['anotherKey'] = 'E';

If a key is not specified, the value will be associated with the largest previously assigned integer key plus one.

// If the largest integer key was 22, the key 
// for the value below would be 23.
$myArray[] = 'F';

Removing Values from an Array

Use the unset() function to remove an item from an array.

unset($myArray[22]);  // Removes the item with key 22

Iterating Through an Array

The foreach operator can be used to iterate over the items in an array.

// Display the current contents of the array
foreach($myArray as $key => $value) {
  echo $key . ' => ' . $value . '<br />';

Multi-Dimensional Arrays

In PHP, a multi-dimensional array can be created by making an array containing other arrays as values.

$multiDimensionalArray = array(
  'A' => array(0 => 'red', 2 => 'blue', 3 => 'green'),
  'B' => array(1 => 'orange', 2 => 'black'),
  'C' => array(0 => 'white', 4 => 'purple', 8 => 'grey')
echo $multiDimensionalArray['A'][3]; // green
echo $multiDimensionalArray['C'][8]; // grey

Back to Tutorials