Evil Elf
Evil Elf

Reputation: 2227

How does PHP keep track of order in an associative array?

When pushing a new value onto an indexed array

$array[] = 'new value';

the PHP documentation explains how it gets added in the [MAX_INDEX+1] position.

When pushing a new value onto an associative array

$array['key'] = 'new value';

it works the same, but I don't see any explanation in the documentation to confirm how or why it does so. The order seems to be consistent in my implementation, but how do I know for sure that the order will remain the same? Does anyone know how PHP implements this on the back-end?

Upvotes: 11

Views: 8350

Answers (4)

Your Common Sense
Your Common Sense

Reputation: 157875

MAX_INDEX actually has nothing to do with ordering.
you can do

$array[5] = 'new value';
$array[1] = 'new value';
$array[105] = 'new value';
$array[2] = 'new value';

and this array will keep that order as well.

PHP array is an ordered map, so, it's a map that keeps the order.
array elements just keep the order since they were added that's all.

Upvotes: 3

cmc
cmc

Reputation: 4413

All PHP Arrays, numeric and associative, are implemented as a so-called "Ordered Hash-Table". This is a data science term which amounts to: "A reasonable fast key-value store that keeps track of the order in which keys and values were inserted". In other words, PHP arrays have a bit of memory bolted on for the purpose of remembering order. Every time you put something in it, PHP automatically puts the order in there as well.

Interestingly, this happens for numeric keys as well- so if you put the values 1,2,3,4,5 into a PHP array, PHP is still separately keeping track of the order. If this sounds wasteful, that's because it is! It does, however, save brain cycles, that can be used to solve other poeple's problems, real and imagined.

Upvotes: 3

n00dle
n00dle

Reputation: 6043

How are associative arrays implemented in PHP? might give you some insight.

It seems that PHP arrays are essentially hash tables, so the order of the array will stay the same until you reorder it (e.g. by sorting the array).

EDIT: It appears this is getting downvoted, allow me to explicitly include the sources I linked to in the comment below here...

Upvotes: 1

Ryre
Ryre

Reputation: 6181

I prefer to rely on ksort. In my experience, arrays stay consistent until you start removing elements. Better to manually sort them and know they're in the order you want.

Upvotes: 0

Related Questions