4 ms·
I got foiled by PHP's deceptive Frankenstein “dictionary or list” ARR (cont)
- Minor49er 5y agotl;dr: PHP arrays are basically hash tables. There's an odd departure towards the end where the author talks about JSON-to-array conversions and vice versa. Unsurprisingly, this can't always work, not only because of the keying issue that the author mentions, but also because PHP supports objects, references, anonymous functions, and other things that JSON simply can't support.
- duskwuff 5y ago> tl;dr: PHP arrays are basically hash tables. Weirder than that. They're ordered hash tables. The order of keys in a PHP array isn't arbitrary, like dictionaries/hashes/maps in various other languages; it's based on the order that keys are added, and can be explicitly manipulated with functions like ksort().
- Minor49er 5y agoRegarding the ordering, you can navigate hash tables in other languages similarly though, can't you?
- theonething 5y agoYes, e.g. in Ruby since 1.9, hash order is guaranteed.
- JodieBenitez 5y agoSame in Python since 3.6 (2016)
- vegai_ 5y agoAlthough the changes doc[1] states that dicts being ordered is an implementation detail that shouldn't be relied on. Nobody does of course ;) [1] https://docs.python.org/3.6/whatsnew/3.6.html#new-dict-implementation https://docs.python.org/3.6/whatsnew/3.6.html#new-dict-imple...
- warvariuc 5y agoAs of Python 3.7, this is no longer an implementation detail and instead becomes a language feature.
- ilyash 5y agoYep. In Next Generation Shell for example. At the time that the language was created, around 2013, it was clear to me (author of the language) that ordered traversal is beneficial and outweighs the downsides (memory usage).
- tyingq 5y agoYou can force json_decode to unwrap into an associative array...there's a flag.
- paco3346 5y agoYa, this is really just the author not fully understanding `json_decode()`
- totony 5y agoPHP developers differentiate between arrays and associative arrays. Although you can mix int and string keys, I've never seen anyone do so in actual code.
- notRobot 5y agoSame. Been using PHP for years, and I've never come across this in the wild. Just because you can do something, doesn't mean you have to.
- duskwuff 5y agoPHP 8.1 even has a function to tell the difference between list-like arrays and associative arrays: array_is_list().
- edudobay 5y agoThough we cannot force PHP to interpret keys as strings if they also represent valid integers. I just had a case of an (associative) array of numeric codes — those which start with a '0' are treated as string keys, all others being treated as numeric. This doesn't matter so much at runtime, but I had to suppress some type checker (Psalm) errors.