Associative arrays

As well as choosing individual values, you can also choose your keys - in the fruits code above we just specify values, but we could have specified keys along with them, like this:

    $myarray = array("a"=>"Apples", "b"=>"Oranges", "c"=>"Pears");

This time, var_dump() will output the following:

array(3) {
    string(6) "Apples"
    string(7) "Oranges"
    string(5) "Pears"

As expected, our 0, 1, and 2 element keys have been replaced with a, b, and c, but we could equally have used "Foo", "Bar", and "Baz", or even variables or other arrays to act as the keys. Specifying your own keys produces what is called an associative array - you associate a specific key with a specific value. Most associative arrays use strings as keys, but do not be afraid to try more advanced things out.

The one exception here is floating-point numbers: these make very poor array indexes. The problem lies in the fact that PHP converts them to integers before they are used, which essentially rounds them down. So, the following code will create an array with just one element in:

    $array[1.5] = "foo";
    $array[1.6] = "bar";

The first line will read 1.5 as the key, round it down to 1, then store "foo" at index 1. The second line will read 1.6 as the key, also round it down to 1, then store "bar" at index 1, overwriting "foo". If you really want to use floating-point numbers as your keys, pass them in as strings, like this:

    $array["1.5"] = "foo";
    $array["1.6"] = "foo";

That should output the following:

array(2) {
    string(3) "foo"
    string(3) "foo"

This time the floating-point numbers have not been rounded down or converted at all, because PHP is using them as strings. The same solution applies to reading values out from an associative array with floating-point keys - you must always specify the key as a string.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: The two ways of iterating through arrays >>

Previous chapter: First steps

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.