Check if array key exists, case insensitive

5.1k views Asked by At

I try to find the right way to check, in a CASE-INSENSITIVE manner, if an array key exists.

I have an array - a list of HTTP headers:

$headers = [
    'User-Agent' => 'Mozilla',
];

Basically, I want to be able to give something like this (with small character 'u'):

$keyExists = array_key_exists('user-Agent', $headers);

and to receive a boolean true when applying a var_dump:

var_dump($keyExists); // I need TRUE to be returned.

Thank you for your help.

3

There are 3 answers

9
Qirel On BEST ANSWER

You can use array_change_key_case() to convert all cases to lower, and check on the lowercase key in array_key_exists(). array_change_key_case() changes all keys to lowercase by default (but you can also change them to uppercase, by supplying the CASE_UPPER to the second argument - CASE_LOWER is default).

This of course means that the key you're looking for, must be lowercase when you're passing it to the first argument of array_key_exists(). You pass a variable through, you can use strtolower() to ensure that it is.

$headers = array(
    'User-Agent' => 'Mozilla',
);
$headers = array_change_key_case($headers); // Convert all keys to lower
$keyExists = array_key_exists('user-agent', $headers);
var_dump($keyExists);

It's worth noting that if you have multiple keys that become the same when they are lowercased (e.g. if you have Foo and foo as keys in the original array), only the last value in the array would remain. As it reads in the manual: "If an array has indices that will be the same once run through this function (e.g. "keY" and "kEY"), the value that is later in the array will override other indices."

5
Sumit Parakh On

You can either use array_change_key_case method (a bit expensive) to convert all keys into lower case and then compare it. Or write your own function for it.

<?php

function lowerCase($header,$compareKey){
    foreach ($header as $key => $value) {
        if(strtolower($key)==strtolower($compareKey)){
            return true;
        }       
    }
    return false;
}

$headers = array(
    'User-Agent' => 'Mozilla',
);

$keyExists = array_key_exists(strtolower('user-Agent'), array_change_key_case($headers,CASE_LOWER));

var_dump($keyExists);

$keyExists2 = lowerCase($headers,'user-Agent');
var_dump($keyExists2);
?>
1
Sachila Ranawaka On

create an array providing a mapping between lowercased and case-sensitive versions

$headers = array(
    'User-Agent' => 'Mozilla',
);
$keys=array_keys($headers);
$map=array();
foreach($keys as $key)
{
     $map[strtolower($key)]=$key;
}

$name=strtolower('user-Agent');
var_dump(isset($map[$name]))