0

I'm learning PHP and I've got a question that's bothering me. PHP arrays seem to be hashmaps internally. If you give an array a key and value, it almost certainly has to put the key through some sort of hashing function before placing it in an actual array, right? Why then, if I give an array a series of keys and values and then dump these to screen, does PHP maintain the order in which I entered the values?

for instance:

$arr = array();
$arr[1] = 'one';
$arr[3] = 'three';
$arr[2] = 'two';

foreach($arr as $key => $val)
    echo "$key => $val<br>"

would render "1 => one, 2 => two, 3 => three" in a typical hashmap, but instead I get "1 => one, 3 => three, 2 => two." Which to me means that there have to be both and order and a key being maintained in whatever datatype this actually is.

Thanks in advance for any explanation.

Frank V
  • 25,141
  • 34
  • 106
  • 144
Ryan
  • 257
  • 4
  • 14
  • 1
    First line in the docs: "_An array in PHP is actually an ordered map. A map is a type that associates values to keys_" http://php.net/manual/en/language.types.array.php So yes, they are ordered. – Michael Berkowski Sep 09 '14 at 19:29
  • Short answer is it's something like javas linkedHashMap – monocell Sep 09 '14 at 19:31

1 Answers1

4

You are correct about the array being stored as a hash table or ordered map. Basically, everything in PHP is a hash table.

See here: Understanding PHP's internal array implementation

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • Right, but a hash table shouldn't keep track of the fact that I added 3 before 2. – Ryan Sep 09 '14 at 19:33
  • Sure. If you look at the link the hash table contains arBucket for buckets that contain pListNext and pListLast for arrays. – AbraCadaver Sep 09 '14 at 19:41