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

--

--

No responses yet