How does PHP track order in an associative array?

When a new value is clicked on an indexed array

$array[] = 'new value'; 

The PHP documentation explains how it is added to the [MAX_INDEX + 1] position.

When a new value is clicked on an associative array

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

it works the same, but I see no explanation in the documentation to confirm how and why this is done. 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 in the background?

+10
php associative-array
source share
4 answers

How are associative arrays implemented in PHP? may give you some idea.

It looks like PHP arrays are essentially hash tables, so the order of the array will remain unchanged until you change it (for example, by sorting the array).

EDIT: It seems like this is happening with a downgrade, let me explicitly include the sources I linked to in the comments below, here ...

  • "Associative PHP arrays are actually an implementation of HashTables," from How is PHP Level Array Implemented?

  • Also from this source: β€œThe PHP array is a chained hash table (searching for O (c) and O (n) in case of key collision), which allows you to use int and string keys. It uses 2 different hashing algorithms to correspond to two types in one same hash key space.

  • "Everything Is HashTable" from http://nikic.imtqy.com/2012/03/28/Understanding-PHPs-internal-array-implementation.html

+1
source share

MAX_INDEX actually has nothing to do with the order.
You can do

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

and this array will keep this order.

A PHP array is an ordered map, that is, a map that maintains order.
array elements just keep order, since they were added that's all.

+3
source share

I prefer to rely on ksort . In my experience, arrays remain unchanged until you start deleting elements. It’s better to manually sort them and find out that they are in the order you want.

0
source share

All PHP arrays, numerical and associative, are implemented as a so-called "ordered hash table". This is a data science term that means: "A smart, fast storage of key values ​​that keeps track of the order in which keys and values ​​were inserted." In other words, PHP arrays have a bit of memory to remember order. Every time you put something into it, PHP automatically brings order there.

Interestingly, this happens for numeric keys as well-, so if you put the values ​​1,2,3,4,5 in a PHP array, PHP will still keep order separately. If this sounds wasteful, then because it is! This, however, preserves brain cycles that can be used to solve other problems of people, real and imaginary.

0
source share

All Articles