By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,719 Members | 1,439 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,719 IT Pros & Developers. It's quick & easy.

case insensitive associative array (tolerant dictionary)

P: n/a
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
lowercase
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)?

Background:
I have some database access code that must work with multiple
databases.
The problem is that some databases return their column metadata in
all caps no matter how the SELECT statement or table schema defined it.

http://www.oracle.com/technology/tec...ml#assocarrays

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);
print $row['my_id'];
print $row['my_string'];
print $row['my_flag'];
Istead, you must access the row record array like this:
print $row['MY_ID'];
print $row['MY_STRING'];
print $row['MY_FLAG'];
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]) )
return $aa[$key];
return $aa[strtoupper($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.

Yours,
Noah Spurrier

Jul 17 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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:

<?php

# untested

$new_ar = array();

foreach ($old_ar as $key => $val)
{
if (!is_array($val))
{
$new_ar[strtolower($key)] = $val;
}
else
{
$new_ar[strtolower($key)] = array();
foreach ($val as $subkey => $subval)
{
$new_ar[strtolower($key)][strtolower($subkey)] = $subval;
}
}
}

?>

Jul 17 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.