Hacker News new | ask | show | jobs
by idoubtit 22 days ago
There's one problem with arrays that I haven't seen mentioned here or by the OP: when inserting a key-value, the type of the key may change. For instance ["4" => "four"] === [4 => "Four"]

This can lead to some unexpected behaviors. For example, I've already been bitten by `array_merge()` whose result is different if its parameters are arrays with numeric indexes.

    array_merge(["4 " => "four"], ["5 " => "five"])
    // ["4 " => "four", "5 " => "five"]

    array_merge(["4" => "four"], ["5" => "five"])
    // [0 => "four", 1 => "five"]
1 comments

The key type changing is generally not a problem per se, but it's definitely odd with the default re-indexing behaviour depending on whether something is integer keys only or not.

That's exactly what I've been complaining in my post above. If there were no automatic reindexing, then this wouldn't be a problem either.

It's surprisingly rare that it becomes a problem, but I've definitely been bit by it before when getting array keys, expecting them to be strings and doing === comparisons.