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.
You can use
array_change_key_case()
to convert all cases to lower, and check on the lowercase key inarray_key_exists()
.array_change_key_case()
changes all keys to lowercase by default (but you can also change them to uppercase, by supplying theCASE_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 usestrtolower()
to ensure that it is.It's worth noting that if you have multiple keys that become the same when they are lowercased (e.g. if you have
Foo
andfoo
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."array_change_key_case()