php: Array keys case *insensitive* lookup?

前端 未结 12 1939
予麋鹿
予麋鹿 2020-12-25 10:30
$myArray = array (\'SOmeKeyNAme\' => 7);  

I want $myArray[\'somekeyname\'] to return 7.
Is there a way to do this

12条回答
  •  粉色の甜心
    2020-12-25 11:06

    In my case I wanted an efficient workaround where my program was already creating the array using a foreach loop from customer data having unknown case, and I wanted to preserve the customer's case for later display in the program.

    My solution was to create a separate array $CaseMap to map a given lowercase key to the mixedcase key used in the array (irrelevant code is omitted here):

    $CaseMap=[];
    foreach ($UserArray as $Key=>$Value)
        $CaseMap[strtolower($Key)]=$Key;
    

    Then lookup is like this:

    $Value=$UserArray[$CaseMap("key")];
    

    and the memory overhead is just the $CaseMap array, which maps presumably short keys to short keys.

    I'm not sure if PHP has a more efficient way to generate $CaseMap in the case where I'n not already using foreach.

提交回复
热议问题