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:
<?php $myarray = array("a"=>"Apples", "b"=>"Oranges", "c"=>"Pears"); var_dump($myarray); ?>
This time, var_dump() will output the following:
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:
<?php $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:
<?php $array["1.5"] = "foo"; $array["1.6"] = "foo"; var_dump($array); ?>
That should output the following:
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.
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
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.