Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: Array keys case *insensitive* lookup?

Tags:

arrays

php

$myArray = array ('SOmeKeyNAme' => 7);   

I want $myArray['somekeyname'] to return 7.
Is there a way to do this, without manipulating the array?

I don't create the array, an thus can not control it's keys

like image 210
shealtiel Avatar asked Nov 21 '10 19:11

shealtiel


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.

Are array keys case-sensitive?

Keys are case sensitive because "key" !== "Key" , because they are different strings.

What is the use of array function Array_change_key_case ()?

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

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.


1 Answers

Option 1 - change the way you create the array

You can't do this without either a linear search or altering the original array. The most efficient approach will be to use strtolower on keys when you insert AND when you lookup values.

 $myArray[strtolower('SOmeKeyNAme')]=7;   if (isset($myArray[strtolower('SomekeyName')]))  {   } 

If it's important to you to preserve the original case of the key, you could store it as a additional value for that key, e.g.

$myArray[strtolower('SOmeKeyNAme')]=array('SOmeKeyNAme', 7); 

Option 2 - create a secondary mapping

As you updated the question to suggest this wouldn't be possible for you, how about you create an array providing a mapping between lowercased and case-sensitive versions?

$keys=array_keys($myArray); $map=array(); foreach($keys as $key) {      $map[strtolower($key)]=$key; } 

Now you can use this to obtain the case-sensitive key from a lowercased one

$test='somekeyname'; if (isset($map[$test])) {      $value=$myArray[$map[$test]]; } 

This avoids the need to create a full copy of the array with a lower-cased key, which is really the only other way to go about this.

Option 3 - Create a copy of the array

If making a full copy of the array isn't a concern, then you can use array_change_key_case to create a copy with lower cased keys.

$myCopy=array_change_key_case($myArray, CASE_LOWER); 
like image 103
Paul Dixon Avatar answered Sep 22 '22 22:09

Paul Dixon