Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP have an ordered dictionary?

Does PHP have an Ordered Dictionary, like that in Python? IE, each key value pair additionally has an ordinal associated with it.

like image 220
Casebash Avatar asked Sep 22 '11 06:09

Casebash


People also ask

Does PHP have dictionary?

There are no dictionaries in php, but PHP array's can behave similarly to dictionaries in other languages because they have both an index and a key (in contrast to Dictionaries in other languages, which only have keys and no index).

What is an ordered dictionary?

It's a dictionary subclass specially designed to remember the order of items, which is defined by the insertion order of keys.

Does dictionary store in order?

Dictionaries do not have a predictable order as their keys are stored by a hash.

Is dictionary an ordered set?

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.


Video Answer


3 Answers

That's how PHP arrays work out of the box. Each key/value pair has an ordinal number, so the insertion order is remembered. You can easily test it yourself:

http://ideone.com/sXfeI

like image 128
reko_t Avatar answered Sep 25 '22 03:09

reko_t


If I understand the description in the python docs correctly, then yes. PHP Arrays are actually only ordered maps:

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

PHP Array docs

like image 37
enricog Avatar answered Sep 25 '22 03:09

enricog


PHP arrays work this way by default.

$arr = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4);
var_dump($arr); // 1, 2, 3, 4

unset($arr['three']);
var_dump($arr); // 1, 2, 4

$arr['five'] = 5;
var_dump($arr); // 1, 2, 4, 5
like image 42
Kaivosukeltaja Avatar answered Sep 24 '22 03:09

Kaivosukeltaja