php: Array keys case *insensitive* lookup?

前端 未结 12 1945
予麋鹿
予麋鹿 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:09

    I also needed a way to return (the first) case-insensitive key match. Here's what I came up with:

    /**
     * Case-insensitive search for present array key
     * @param string $needle
     * @param array $haystack
     * @return string|bool The present key, or false
     */
    function get_array_ikey($needle, $haystack) {
        foreach ($haystack as $key => $meh) {
            if (strtolower($needle) == strtolower($key)) {
                return (string) $key;
            }
        }
        return false;
    }
    

    So, to answer the original question:

    $myArray = array('SOmeKeyNAme' => 7);
    $test = 'somekeyname';
    $key = get_array_ikey($test, $myArray);
    if ($key !== false) {
        echo $myArray[$key];
    }
    

提交回复
热议问题