Reputation: 1557
While looking through some code and attempting to fix some issues I came to a question. Why are PHP array keys case sensitive? It would seem beneficial to have
$array = array(
"Key"=>"Value",
"key"=>"Value",
)
be the same key. Can someone explain to me the benefit of having those two keys separated?
Upvotes: 10
Views: 5807
Reputation: 322
PHP has no built-in encoding of text strings. While there are functions that support various encodings, especially UTF8 and related encodings, for the most fundamental parts of a language a string is just a series of bytes. There aren't any built in assumptions about things like how many bytes are in a character, what bytes are allowed, or indeed which characters are related by being the upper/lower case versions of the same letter.
So to make array keys case insensitive in a reliable way the array handling functions would need to document the encoding and possibly collation used for string keys. To be widely useful they might need to make those options available to programmers, and allow turning off case sensitivity, e.g. for people who use non-textual binary strings, or binary strings in mixed encodings or encodings that the function does not support as array keys.
PHP version 6 was an attempt to build unicode-encoded string handling in to the core of the language. But the project ran into serious problems, and so there was never a full release of PHP 6.
Upvotes: 1
Reputation: 8492
PHP arrays are implemented with hash tables. The way a hash table works, to first order: it hashes the input and uses that as an index to find the right memory location to insert an object.
Now imagine your arrays are case-insensitive. Rather than doing a single hash lookup, you now have to do 2^(length of your string) hash lookups. Furthermore, of these locations, which one do you choose? Suddenly your elegant, simple hash table has become much more complicated, both computationally and in its implementation.
Furthermore, in most other languages, Key
and key
are treated differently. PHP certainly doesn't always adhere to the principle of least surprise, but in this case it does -- and that's how it should be.
As other users have pointed out, this behavior is easy to obtain if you desire it: simply convert your keys to lowercase before inserting and/or referencing them.
Upvotes: 22