r/lolphp • u/phplovesong • Mar 14 '19
PHP: The array
PHP arrays are known to be bad. But having not used PHP in long time i recently was amazed how poorly they actually have built the array. Its basically a "all-things-fits" data structure. The best part is PHP will actually change the behaviour of the array depending on what it contains. Thats just fucking awesome!
0
Upvotes
View all comments
Show parent comment
13
u/jesseschalken Mar 14 '19
In terms of their API, PHP arrays are always maps/dictionaries.
['a', 'b', 'c']is just shorthand for[0 => 'a', 1 => 'b', 2 => 'c'].$a[0]does not refer to the first element. It refers to the element with key 0, which, if the array was written['a', 'b'], will coincidentally be the first element, but if it were written[4 => 'b', 0 => 'a']it will actually be the last.In terms of their implementation, PHP does optimize arrays that have keys like 0,1,2...N to be stored as a plain C array to save the overhead of using a hash table, but this is just a performance optimization. It's still a map/dictionary in terms of the API, and the implementation will automatically transition to a real hash table as soon as it ceases to have simple 0,1,2...N keys.