Share via:

PHP: Associative Arrays

In PHP all arrays can be Associative. In this tutorial, you will learn how to create an association between keys and values in arrays.


Edited: 2019-11-03 05:10

PHP Tutorial

An Associative Array is simply an array where there is a relationship between the keys and the values in the array. This is also known as mapping.

In PHP, it does not matter if you use integers or strings as keys, since PHP does not distinguish between indexed and associative array types. You could even use a mix of strings and numbers as keys—it would not matter!

One use of associative arrays is to indicate an association between a key and a value pair, usually meaning that the key should not be changed, and you should avoid using build-in PHP functions that does not preserve the array keys.

Taking a very basic example, using a single-dimensional array to store names and e-mail addresses of some of PHP's creators:

$teachers = array(
 'Rasmus Lerdorf' => '',
 'Zeev Suraski' => '',
 'Andi Gutmans' => ''

To store more more information for each teacher, such as the year the teacher was born, we could use a two-dimensional array like this:

$teachers = array(
 'Rasmus Lerdorf' => array('e-mail' => '', 'born' => '1968'),
 'Zeev Suraski' => array('e-mail' => '', 'born' => '1976'),
 'Andi Gutmans' => array('e-mail' => '', 'born' => '1972')

Traversing associative arrays

To traverse the arrays, we can use a foreach or other loop construct.

But first, let us iterate over the single-dimensional version:

foreach ($teachers as $teacher => $email) {
  echo PHP_EOL . $teacher . ':' . $email;



To loop through multi-dimensional arrays can be a challenge, especially if we do not know the level of nesting the array is going to have. However, for a simple two-dimensional array like ours, we could just "hard-code" the code dealing with the second arrays:

foreach ($teachers as $teacher => $data) {
    echo PHP_EOL . $teacher . PHP_EOL .
        ' E-mail: ' . $data['e-mail'] . PHP_EOL .
        ' Born: ' . $data['born'];


Rasmus Lerdorf
 Born: 1968
Zeev Suraski
 Born: 1976
Andi Gutmans
 Born: 1972