Skip to content
Advertisement

Change last key (dynamically named) in a multidimensional array in PHP [closed]

If my array looks like:

$array['foo']['bar']['this'] = 'something';
Array
(
    [foo] => Array
        (
            [bar] => Array
                (
                    [this] => something
                )

        )
)

How do I change the value of [this] from something to something_else? The array can always have different keys. Other examples:

$array1['test']['that'] = 'something';
$array2['yet']['a']['deeper']['example'] = 'something';

I want to change the last inner key. The results should be:

Array
(
    [foo] => Array
        (
            [bar] => Array
                (
                    [this] => something_else
                )

        )
)

Array
(
    [test] => Array
        (
            [this] => something_else
        )
)

Array
(
    [yet] => Array
        (
            [a] => Array
                (
                    [depper] => Array
                             (
                                  [example] => something_else
                             )
                )

        )

)

Advertisement

Answer

You can use a recursive call and access the array using a reference:

<?php
    function recursiveCall(array &$array, $newValue) {
        foreach ($array as $key => &$value) {
            if (is_array($value)) {
                recursiveCall($value, $newValue);
            } else {
                $value = $newValue;
            }
        }
    }

    $array['foo']['bar']['this'] = 'something';
    print_r($array);
    recursiveCall($array, 'tralala');
    print_r($array);
?>

Output:

//input array
Array
(
    [foo] => Array
        (
            [bar] => Array
                (
                    [this] => something
                )

        )

)

//output array
Array
(
    [foo] => Array
        (
            [bar] => Array
                (
                    [this] => tralala
                )

        )

)

This would work with any dimension and any key name.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement