Php change array keys recursive

I have this trimmer function, it recursively trims all values in array [people put tons of spaces for no reason!]:

function trimmer[&$var] {
    if [is_array[$var]] {
        foreach[$var as &$v] {
            trimmer[$v];
        }
    }
    else {
        $var = trim[$var];
    }
}
trimer[$_POST];

PROBLEM: I would like to add new feature: i want this function also to convert all _ [underscore] in keys to spaces. I know how to convert keys [str_replace['_', ' ', $key]], but i have trouble to make it work in this recursive style...

Input:

$_POST['Neat_key'] = '   dirty value ';

Expected result:

$_POST['Neat key'] = 'dirty value';

asked Aug 16, 2012 at 18:53

2

Unfortunately, there isn't a way to replace the keys of an array while you loop the array. This is a part of the language, the only way around it is to use a temporary array:

$my_array = array[
    'test_key_1'=>'test value 1     ',
    'test_key_2'=>'        omg I love spaces!!         ',
    'test_key_3'=>array[
        'test_subkey_1'=>'SPPPPAAAAACCCEEESSS!!!111    ',
        'testsubkey2'=>'    The best part about computers is the SPACE BUTTON             '
    ]
];
function trimmer[&$var] {
    if [is_array[$var]] {
        $final = array[];
        foreach[$var as $k=>&$v] {
            $k = str_replace['_', ' ', $k];
            trimmer[$v];
            $final[$k] = $v;
        }
        $var = $final;
    } elseif [is_string[$var]] {
        $var = trim[$var];
    }
}
/* output
array [
        'test key 1'=>'test value 1',
        'test key 2'=>'omg I love spaces!!',
        'test key 3'=>array [
                'test subkey 1'=>'SPPPPAAAAACCCEEESSS!!!111',
                'testsubkey2'=>'The best part about computers is the SPACE BUTTON'
        ]
]
*/

Try it: //codepad.org/A0N5AU2g

answered Aug 16, 2012 at 19:09

Chris BakerChris Baker

48.9k12 gold badges98 silver badges115 bronze badges

0

This is an oldie but I just saw it in related:

function trimmer[&$var] {
    if [is_array[$var]] {
        foreach[$var as &$v] {
            trimmer[$v];
        }
        // only additional code
        $var = array_combine[str_replace['_', ' ', array_keys[$var]], $var];
    }
    else {
        $var = trim[$var];
    }
}

But better nowadays would be array_walk_recursive[].

answered Apr 2, 2015 at 20:34

AbraCadaverAbraCadaver

77.5k7 gold badges63 silver badges84 bronze badges

1

[PHP 5 >= 5.3.0, PHP 7, PHP 8]

array_replace_recursiveReplaces elements from passed arrays into the first array recursively

Description

array_replace_recursive[array $array, array ...$replacements]: array

array_replace_recursive[] is recursive : it will recurse into arrays and apply the same process to the inner value.

When the value in the first array is scalar, it will be replaced by the value in the second array, may it be scalar or array. When the value in the first array and the second array are both arrays, array_replace_recursive[] will replace their respective value recursively.

Parameters

array

The array in which elements are replaced.

replacements

Arrays from which elements will be extracted.

Return Values

Returns an array.

Examples

Example #1 array_replace_recursive[] example

The above example will output:

Array
[
    [citrus] => Array
        [
            [0] => pineapple
        ]

    [berries] => Array
        [
            [0] => blueberry
            [1] => raspberry
        ]

]
Array
[
    [citrus] => Array
        [
            [0] => pineapple
        ]

    [berries] => Array
        [
            [0] => blueberry
        ]

]

Example #2 array_replace_recursive[] and recursive behavior

The above example will output:

Array
[
    [citrus] => Array
        [
            [0] => pineapple
        ]

    [berries] => Array
        [
            [0] => blueberry
            [1] => raspberry
        ]

    [others] => litchis
]

See Also

  • array_replace[] - Replaces elements from passed arrays into the first array
  • array_merge_recursive[] - Merge one or more arrays recursively

Gregor at der-meyer dot de

13 years ago

Nice that this function finally found its was to the PHP core! If you want to use it also with older PHP versions before 5.3.0, you can define it this way:



I called this function array_merge_recursive_overwrite[] in my older projects, but array_replace_recursive[] sounds quite better while they do the same.

If you implemented such a compatible function before and don't want to refactor all your code, you can update it with the following snippet to use the native [and hopefully faster] implementation of PHP 5.3.0, if available. Just start your function with these lines:

Pau Prat Torrella

2 years ago

Note that function will NOT replace a sub-tree from you $array1 if its value in $array2 is an empty array.
Even tho the key for this dimension is technically 'set'.

[I suppose it treats it as just another recursive level to dive in, finding no key to compare, backtracking while leaving this sub-tree alone]

For example:

$array1  = ['first' => ['second' => 'hello']];
$array2  = ['first' => []];             
$result = array_replace_recursive[$array1, $array2];

$result is still: ['first' => ['second' => 'hello']].

David Spector

1 year ago

It seemed to me that the first argument is passed by reference, so it will contain the results of this operation, but experiment shows that this is not true. The array value from the first argument is modified by each succeeding argument, and the result is returned to the caller. The array passed as the first argument is not modified.

Uther

3 years ago

Note that the use of the word "replace" in the function's description is a bit misleading... as none of the parameters are passed by reference, it does not actually replace anything... this simply describes from which parameter the resulting values come.

msahagian at dotink dot org

10 years ago

This is a fairly concise version which does not rely on traditional recursion:

kyle [dot] florence [@t] gmail [dot] com

13 years ago

This might help out people who don't have 5.3 running:

oliver dot coleman at gmail dot com

7 years ago

If you came here looking for a function to recursively find and replace [scalar] values in an array [also recurses through objects]:

Chủ Đề