PHP Phun #2: Array Methods
PHP Phun #2: Arrays (And Wonked Up Array Methods)
The Topic: Every Array is Associative
People (rightly and justifiably) love to give PHP grief for its native array methods. There’s a ton of inconsistencies on function arguments and function return values that feel unintuitive.
Even apart from array functions themselves, there’s a lot of confusion about arrays in general. The one thing you must remember, above all, is that all arrays in php are hash tables.
ALL arrays are key-value maps. They are all associative arrays. Even if you’re just shoving values into an array without specifying keys, it’s still an associative array; php has just decided to be nice enough to give you keys that happen to be consecutive integers starting from zero.
Even though I know that all php arrays are associative arrays, some odd and unexpected consequences of this still get me.
The Problem: The Return of Array Filter
I was investigating the cause of a bug when I nailed it down to the return value of an array_filter call. A rough approximation of the code was something like this:
$filteredElement = array_filter(function ($element) {....}, $array)[0];
Now with this filter, I was 100% certain that the function would always return exactly one value, but for some reason there were times where $filteredElement was null. If I knew I was always getting a value back, why was it empty?
Well, because the return of array_filter is an associative array and it preserves the original naming of the keys.
Let’s say the array I passed in was this one:
[‘zelda’, ‘link’, ‘gannon’]
Under the hood, that’s secretly:
[ ‘0’ => ‘zelda’, ‘1’ => ‘link’, ‘2’ => ‘gannon’].
If my array_filter returned back the ‘gannon’ element, the array I’d be getting back would actually be:
[ ‘2’ => ‘gannon’].
This is not what’d you’d expect, as a lot of other languages would give you back
[ ‘0’ => ‘gannon’ ].
Because I was getting back [ ‘2’ => ‘gannon’], I wasn’t getting anything when I tried to access the element with zero as my key, [0].
One thing you can do to prevent this is wrap the array_filter in array_values. This will take all the values from the array and put them in a new array with numeric, sequential indexed keys.









