how to access a value in php array using case insensitive index. like
$x = array('a'=>'ddd');
any function to access it using $x['A'];
That is just not the way strings / array work, in PHP.
In PHP, "a" and "A" are two different strings.
Array keys are either integers or strings.
So, $a["a"] and $a["A"] point to two distinct entries in the array.
You have two possible solutions :
In the first case, you'll have to use strtolower() each time you want to access an array-item :
$array[strtolower('KEY')] = 153;
echo $array[strtolower('KEY')];
In the second case, mabe something like this might work :
(Well, this is a not-tested idea ; but it might serve you as a basis)
if (isset($array['key'])) {
// use the value -- found by key-access (fast)
}
else {
// search for the key -- looping over the array (slow)
foreach ($array as $upperKey => $value) {
if (strtolower($upperKey) == 'key') {
// You've found the correct key
// => use the value
}
}
}
But, again it is a bad solution !
I would use OOP here, either extend ArrayObject or implement ArrayAcess and then in the offset methods use relevant string functions to match either case.
This is AFAIK the only way to be able to access it using $x['A']; syntax.
Of course I show no interest here in optimizing for speed. You should have to decide if speed or readable code is your primary goal.
Example:
class MyArray extends ArrayObject {
public function offsetGet($index) {
if ($this->offsetExists($index)) {
return parent::offsetGet($index);
}
if ($this->offsetExists(strtolower($index))) {
return parent::offsetGet(strtolower($index));
}
if ($this->offsetExists(strtoupper($index))) {
return parent::offsetGet(strtoupper($index));
}
return null;
}
}
$x = array('a'=>'ddd');
$x = new MyArray($x);
echo $x['A'];
Output:
ddd
Easy.
Don't do it.
Obfuscating your own code is not a brilliant idea.
Just follow syntax rules and you'll be okay.
array_change_key_case on anything causes long term problems on any code base as there's a need to add strtolower calls all over the place, and soon it starts creeping in unrelated parts of the codebase (which might not be case insensitive).I guess without changing your current array usage would be something like this:
$x = array('a'=>'ddd');
echo isset($x['a']) ? $x['a'] : $x['A'];
You could have this a function like following:
$x = array('a'=>'ddd');
echo getIndex($x, 'a');
// return either the value of $x['a'], $['A'] or null
function getIndex($array, $index) {
return isset($x[strtolower($index)]) ? $x[strtolower($index)] : (isset($x[strtoupper($index)]) ? $x[strtoupper($index)] : null);
}
You can use array_change_key_case to change the key case of your array, convert all keys to lower case or upper case and have your peace of mind.
example:
$headers = getallheaders();
$headers = array_change_key_case($headers, CASE_UPPER);
if (isset($headers['AUTHENTICATION'])) {
// do your thing
}