9

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Hydra IO
  • 1,537
  • 1
  • 13
  • 28
  • 7
    Keys are case sensitive because `"key" !== "Key"`, because they are different strings. – gen_Eric Oct 28 '13 at 22:25
  • 7
    I think the onus would be on someone to explain what the benefit of making them case-insensitive would be. Adding case insensitivity would slow lookups down - if you want them to be case-insensitive, just convert your key to lower-case before using it. – halfer Oct 28 '13 at 22:25
  • 1
    The benefit would be not needing to make sure users input their data in the proper case... for instance in url strings: file.php?var1=37&Var2=73&VAr=9 – Rob Cozzens Oct 28 '13 at 22:29
  • 1
    PHP associative arrays are effectively hash maps. And most people expect those to treat strings in a case-sensitive way.. – lethal-guitar Oct 28 '13 at 22:29
  • @RobCozzens well that example of yours is a very specific use case. PHP arrays are meant to be generic. And you can always lowercase that URL string as halfer suggested, it's just one line of code. – lethal-guitar Oct 28 '13 at 22:31

1 Answers1

18

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.

Community
  • 1
  • 1
Christian Ternus
  • 8,406
  • 24
  • 39