Philipp Spinnler
Philipp Spinnler

Reputation: 41

PHP return reference from recursive function

I'm trying to make a recursive function which searches a specific element by value (blubb) in a multidimensional array and returns it as a reference. But my first thought does not work. I'm sure I just missed something simple.

$array = [
    'obj1' => [
        'attr1' => "blubb",
        'attr2' => "bla"
        ],
    'obj2' => [
        'attr1' => "blabb",
        'attr2' => "bla"
        ]
    ];

$node = changeAttr2($array);
$node["attr2"] = "blu";

print_r($node);
print_r($array);

function changeAttr2(&$input) {
    foreach($input as &$value) {
        if ($value === "blubb") {
            return $input;
        }

        return changeAttr2($value);
    }
}

Output:

Array
(
    [obj1] => Array
        (
            [attr1] => blubb
            [attr2] => bla
        )

    [obj2] => Array
        (
            [attr1] => blabb
            [attr2] => bla
        )

)

Expected Output:

Array
(
    [obj1] => Array
        (
            [attr1] => blubb
            [attr2] => blu
        )

    [obj2] => Array
        (
            [attr1] => blabb
            [attr2] => bla
        )

)

Upvotes: 1

Views: 128

Answers (1)

apokryfos
apokryfos

Reputation: 40653

You pass the array by reference but when you return it you're not actually returning a reference.

Do this (honestly this looks very dirty and needs rethinking but this is how you do it if you really really need to):

<?php
$array = [
    'obj1' => [
        'attr1' => "blubb",
        'attr2' => "bla"
        ],
    'obj2' => [
        'attr1' => "blabb",
        'attr2' => "bla"
        ]
    ];

$node = &changeAttr2($array);
$node["attr2"] = "blu";

print_r($node);
print_r($array);

function &changeAttr2(&$input) {
    foreach($input as &$value) {
        if ($value === "blubb") {
            return $input;
        }

        return changeAttr2($value);
    }
}

Prints:

Array
(
    [obj1] => Array
        (
            [attr1] => blubb
            [attr2] => blu
        )

    [obj2] => Array
        (
            [attr1] => blabb
            [attr2] => bla
        )

)

Reason is you need to return the reference and use it as a reference.

more detail in the manual on returning references

Upvotes: 1

Related Questions