Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are php array keys case sensitive?

Tags:

php

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?

like image 559
Hydra IO Avatar asked Oct 28 '13 22:10

Hydra IO


People also ask

Are PHP array keys case sensitive?

Since PHP arrays internally use hash tables, where the array keys are case-sensitive hashed values, it is impossible that one day you will be able to use associative arrays with case-insensitive keys.

What is case-insensitive in PHP?

Summary. PHP is partially case-sensitive. PHP constructs, function names, class names are case-insensitive, whereas variables are case-sensitive.

Which function is used to change key case PHP array?

The array_change_key_case() function changes all keys in an array to lowercase or uppercase.

Is post case sensitive in PHP?

Yes, PHP is case sensitive. However, this is not applicable to user defined functions.


1 Answers

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.

like image 72
Christian Ternus Avatar answered Oct 22 '22 19:10

Christian Ternus