Recursively replace keys in an array

I can't handle it ...

I was hoping there would be a default PHP function for this, but it seems not. The code I found on the Internet does not seem to really work for my situation, as often people only need to change the values ​​of the array, not their keys.

I basically need a recursive function that replaces every key that starts with "_" with the same key without this character ....

Has anyone here used something like this before?

+5
source share
1 answer

Try the following:

function replaceKeys(array $input) {

    $return = array();
    foreach ($input as $key => $value) {
        if (strpos($key, '_') === 0)
            $key = substr($key, 1);

        if (is_array($value))
            $value = replaceKeys($value); 

        $return[$key] = $value;
    }
    return $return;
}

So this code:

$arr = array('_name' => 'John', 
             'ages'  => array(
                  '_first' => 10, 
                  'last'   => 15));

print_r(replaceKeys($arr));

Will be produced (as shown on codepad ):

Array
(
    [name] => John
    [ages] => Array
        (
            [first] => 10
            [last] => 15
        )

)
+17
source

All Articles