Converting lowercase_with_underscores to camelCase

· 263 words · 2 minute read

I have a case where I’m retrieving an array of associative arrays from a database as shown below:

    \[0\] => Array
            \[id\] => 1
            \[some\_id\] => 100001
            \[some\_company\_name\] => Foo
            \[name\] => Bar
            \[created\] => 2008-12-25 21:13:58
            \[last\_updated\] => 2008-12-30 23:32:43


…but I need to represent this structure in XML. I have a pre-defined standard in my XML request/response that the element names are to be camel cased.

Aliasing the field names at the query level is just…a hack. So, I needed a way to convert “foo_bar_baz” to “fooBarBaz” before adding the XML element.

To do this, you can use preg_replace_callback() as shown below, which uses a callback function on every match found.

class FooController
    public function barAction()
        $dao = new Some\_Dao();
        $rows = $dao->getWhateverRows();

        foreach ($rows as $row) {
            foreach ($row as $key => $value) {
                // $key is "foo\_bar\_baz"
                $key = preg\_replace\_callback(
                    array($this, '\_convertToCamelCase'),

            // $key is now "fooBarBaz"

    private function \_convertToCamelCase(array $matches)
         return ucfirst($matches\[1\]);

There is an e modifier that can be used with preg_replace(), but that requires the replacement string to be a valid string of PHP code. This forces the interpreter to parse the replacement string into PHP on each iteration, which can be quite inefficient. Instead, the preg_replace_callback() uses a callback function, which only needs to be parsed once.

I suppose you could easily do the reverse, though I haven’t had a need to write that code yet. :) But…there you go! A little end-of-year tip from myself and the preg_replace() examples.