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.

43 views

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' => 'rasmus.l@example.com',
 'Zeev Suraski' => 'zeev.s@example.com',
 'Andi Gutmans' => 'andi.g@example.com'
);

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' => 'rasmus.l@example.com', 'born' => '1968'),
 'Zeev Suraski' => array('e-mail' => 'zeev.s@example.com', 'born' => '1976'),
 'Andi Gutmans' => array('e-mail' => 'andi.g@example.com', '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;
}

Output:

Rasmus Lerdorf:rasmus.l@example.com
Zeev Suraski:zeev.s@example.com
Andi Gutmans:andi.g@example.com

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'];
}

Output:

Rasmus Lerdorf
 E-mail: rasmus.l@example.com
 Born: 1968
Zeev Suraski
 E-mail: zeev.s@example.com
 Born: 1976
Andi Gutmans
 E-mail: andi.g@example.com
 Born: 1972

Comments