Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
May 26, 2005, 7:37 pm
rate this thread
Can anyone think of a way to make array keys case insensitive?
An option on any recent PHP would be to convert all array keys to
using the standard array_change_key_case() function.
As it turns out, I'm stuck on a PHP 4.1.3 system, so that
function is not available to me. Can anyone think of an
efficient way to write my own version of this function?
Can I edit keys in place without copying the values, or
will I have to copy the entire array (both keys and values)?
I have some database access code that must work with multiple
The problem is that some databases return their column metadata in
all caps no matter how the SELECT statement or table schema defined it.
The following PHP-PEAR code fails on Oracle:
$row = $this->db->getAll ("SELECT my_id, my_string, my_flag
FROM my_table WHERE my_id=" . $key_id);
Istead, you must access the row record array like this:
This would be a simple problem if I only needed to deal with Oracle.
I would just add strtoupper() all my keys before using them.
But then this code would not work on MySQL and PostgreSQL.
I could write a wrapper function like this:
function aa_get_i($aa, $key)
if ( isset($aa[$key]) )
But I was hoping there is something more clever that I could do.
Also this isn't strictly a case insensitive array get.
If I find some other database that converts to all lowercase then
I have to add another test.
Re: case insensitive associative array (tolerant dictionary)
You can always just loop through the array, and build another array as
you go with lowercase keys. This might not be the most elegant way,
but it's pretty straightforward and easy.
This should work if you have an array of scalar values, or a
2-dimensional array also:
$new_ar = array();
foreach ($old_ar as $key => $val)
$new_ar[strtolower($key)] = $val;
$new_ar[strtolower($key)] = array();
foreach ($val as $subkey => $subval)
$new_ar[strtolower($key)][strtolower($subkey)] = $subval;