1

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
        )

)
1
  • Your function does not return a reference. Read the documentation page about how to return references. Commented Jan 11, 2018 at 9:22

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you alot. I know it is super dirty an I'm going to rethink it. But for now this helps to create a prototype.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.