Jason G
Jason G

Reputation: 13

PHP - Searching a multidimensional array and returning a reference to the result

I am trying to write a function that searches a multidimensional array for an array with an certain ID, then returns a reference to that found array. I've come up with this, but it's not working as I expected.

$list = array(
    "id"=>"123",
    "items"=>array(
        "id"=>"456"
    )
);

function &getArrayById(&$array, $id) {

    //Found
    if(isset($array["id"]) && $array["id"] == $id) {
        return $array;
    }

    //Not found, looking for nested array
    foreach(array_keys($array) as $key) {

        if (gettype($array[$key]) === "array") {

            $o = getArrayById($array[$key], $id);

            if(gettype($o) != "NULL") {
                return $o;
            }

        }

    }

    //Not found - end
    return null;
}


$a =& getArrayById($list, "456");
$a["id"] = "ID EDITED";
echo $list["items"]["id"]; //"456" - not "ID EDITED" like I want

One thing I noticed is that when I search using an id of 123 (i.e. the very top level of the array), attempting to edit the returned array's id with $a works as expected, so I'm wondering if it's the recursion that's not working as I expect.

Upvotes: 1

Views: 66

Answers (1)

trincot
trincot

Reputation: 350760

Indeed, the recursive call also needs the "assignment by reference" ( =& ):

$o =& getArrayById($array[$key], $id);

It is one of those things in PHP... Having the & prefix at the function definition is not enough on its own, as stated in the documentation:

Note: Unlike parameter passing, here you have to use & in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done

Upvotes: 1

Related Questions