What are associative arrays in PHP?

Arrays are a primitive type of PHP.

You can use arrays in your code in three different ways:

  • As ordered lists,
  • as maps or associative arrays,
  • or as ordered maps (a combination of the two).

(Are you new to PHP and you want to learn about arrays and other basic PHP functionalities as quickly as possibble? Take a look at my beginners’ course to get started).

Maps, or associative arrays, are collections of key => value pairs.

In other words, an associative array is a structure containing some keys, where each key is associated with a value.

For example:

$item = [];
$item['price'] = 2.5;
$item['name'] = "Milk";
$item['available'] = true;

In this example, $item is a PHP array used as an associative array.

$item contains three key => value pairs:

  • [key] price => [value] 2.5
  • [key] name => [value] “Milk”
  • [key] available => [value] true

You can access the value of a specific key of the array by using the following syntax:

echo $item['name']; // output: Milk

In PHP, associative arrays are always ordered.

This means that you can iterate through the array elements in the same order as they have been added (unless they have been rearranged).

For example:

foreach ($item as $key => $value) {
   echo $key . ' -> ' . $value . '<br>';
price -> 2.5
name -> Milk
available -> 1

Key and value types

Array keys can be integers, floats, strings and Boolean.

However, I suggest you stick with integers and strings only, because PHP casts floats and Boolean to integers and using those types can easily cause coding mistakes (as well as making your code less readable).

Usually, integer keys are used for ordered lists, while strings are used for associative arrays.
However, PHP does not differentiate between the two so it’s just a matter of your personal preference.

I suggest you do not mix integers and strings for keys though, because that can cause subtle bugs.

For example, numeric strings are casted to integers when used for array keys so you can overwrite elements by mistake if you use both:

$myArray = [
   10 => 'First element',
   "10" => 'Second element'
Array ( [10] => Second element )

Values, on the other hand, can be of any type (including other arrays to create multi-dimensional arrays, objects and user-defined types).

Let me know if you have any questions by leaving a comment below.


Leave a Comment