Hacker News new | ask | show | jobs
by mdavid626 26 days ago
If I have an “array” and can do array[0] to get first item, but when I filter this array and array[0] throws an error, that’s super weird. What is the meaning of [] or what is an array even? The language forces me to understand how it is implemented under the hood. That’s exactly what the author says: leaky abstraction.
2 comments

That also often shoots you as when json_encoding it only becomes an array when ordered "correctly" (numeric 0-based keys without gaps), otherwise an object. So to be safe you generally need to array_values after filtering. If in your testdata you only remove elements from the end you don't catch that before production data hits.

To get the first element there also is reset().

I love PHP though.

It's especially problematic when encoding an empty object to json. By default an empty array is serialized as [], to get {} you either need to pass a flag to force object serialization (which can mess up serializing actual arrays), or cast the array as an object. Neither of which are great when the object is deeply nested in the serialized object.
An “array” in PHP is an ordered map.
Isn't exactly their complaint? It's called an array, referred to consistently everywhere as an array, but it just ... isn't.
Apparently array is short for associated array:-)
In PHP the array index supports different key types and there's various optimizations that need to happen when the indexes are all numeric, mixed, or all strings or anything else. Technically it's called associative as soon as even one of the indexes isn't numeric. Internally though they are always numeric and anything non integer is hashed internally with DJB2 (Daniel J. Bernstein) hash algorithm and then stored. Using a non numeric index is slightly slower for that reason.
But even if you only have numeric keys, those keys don't need to be consecutive, or start at 0.
Better than calling it a hash.
I don't think it is, tbh.

Perl's hashes are a complete mystery to me still, but at least it lets me know that it's not just a linear, uh, well, array.

> Perl's hashes are a complete mystery to me still

They're unordered mappings from strings to arbitrary values ("scalars" in Perl jargon). In this sense they're just like an object in JavaScript.

Where this gets a little weird is that Perl arrays and hashes are fundamental types distinct from scalars - you can't put a hash into a $variable without taking a reference to it first, for instance. But that's more a matter of Perl being picker about the value/reference distinction than a hash-specific thing.

PHP arrays are vectors, hash maps and doubly linked lists in one
My issue is a ton of people call all maps a hash regardless how it's implemented.
With good abstraction the implementation can be swapped without many noticing.

However PHP leaks different aspects hear and there, making this harder ...