Search code examples
phpcase-sensitivearray-key

Make array keys insensitive in php


Am using DB2 with my PHP. DB2 returns all column names in UPPERCASE. If I use db2_fetch_assoc, then the result would be like this

Array { [USERID] => 4 }

But in my php file, the array values assigned like this and its in camelstyle

$this->userId = $row['userId'];

So it throws the error Error : Undefined index userId

I can use array_change_key_case() function to convert the array to lowercase. But I have hundreds of files which get and assign the array values.

Its not possible to change in all of my files. Also its linux machine.

So is there any function available in php to disable the case sensitivity of array keys.


Solution

  • You can extend ArrayObject from the SPL. This way at least you only have to "touch" the functions/methods that get the data from the database.

    $row = getRow();
    echo $row['userId'];
    
    function getRow() {
        $row = array ( 'USERID' => 4, 'FOO'=>123, 'BAR'=>456 );
        return new UCArrayObject($row);
    }
    
    class UCArrayObject extends ArrayObject
    {
        public function offsetExists ($index) { return parent::offsetExists(strtoupper($index)); }
        public function offsetGet($index) { return parent::offsetGet(strtoupper($index)); }
        public function offsetSet ($index, $newval) { parent::offsetSet(strtoupper($index), $newval); }
        public function offsetUnset ($index) { parent::offsetUnset(strtoupper($index)); }
    }