Adrienne Domingus
2 min readJan 17, 2021

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?

  • First, the docs. They’re helpful!
  • If you create an array like you would in another language, it generates something more akin to a dict, where the keys are an int representing the index, and the value is whatever you provided. This behaves like arrays you’re familiar with, and is written in code like you’re familiar with, but looks a little funky if you print it out:
php > $arr = ["a", "b", "c"];
php > echo var_dump($arr);
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
  • You can create an array with keys that you define, though the keys are limited to strings and integers (with type casting for booleans and null values)
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!