Arrays in PHP…Because there are no hashes/dicts

Say What Now?

I’m brand new to PHP. Every other language I’ve worked in has had the concept of a hash/dictionary/object, separate from the concept of an array/list (though, yes, lots of names for the same general idea…I’m going to use the word dict going forward, but I also mean the hash, map, Object, etc. that you’re familiar with).

So I was pretty surprised to learn that the concept of a dictionary doesn’t exist in PHP. They’re useful, and they’re way more time-efficient than arrays in some use cases. So…how does this work?

php > $arr = ["a", "b", "c"];
php > echo var_dump($arr);
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
php > $arr = [2=>"a", 3=> "b", 4=>"c"];
php > echo var_dump($arr);
array(3) {
[2]=>
string(1) "a"
[3]=>
string(1) "b"
[4]=>
string(1) "c"
}

So How Efficient Are They?

So, okay. Functionally, a PHP array stores key/value pairs and handle the dict use case. Do they meet our efficiency use-case too?

TLDR: yes

Data

Determining membership in a collection is way more efficient in a dict, since unlike an array, you don’t need to iterate through the entirety of the collection.

In Python, to determine membership 10k times in a list (array) containing 10k items took ~45 seconds (😬), while to do the same thing (determine whether a key was present) in a dict took ~.01 seconds

In PHP, to determine membership 10k times in an array containing 10k items (effectively determining whether a value was present) took ~5 seconds, while determining whether a key was present took ~.05 seconds

Summary

To wrap-up: For all intents and purposes, PHP does have both arrays and dicts. They just happen to use a data structure called an array for both, and square-bracket syntax for both. It always stores key/value pairs, but defining the keys is optional, falling back to incrementing integers. Carry on!

Senior Software Engineer | www.adriennedomingus.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store