Is it possible, in a function, to return the reference to an array index?

Asked

Viewed 58 times

1

The idea is to have a function that receives a array and return the reference to an index of the same, for example:

$list = ['a', 'b', 'c', 'd', 'e'];

function ref(&list) {
    return &$list[3] ?? false;
}

The use would be in a recursive function to fetch a value in its elements, to change (or not):

$list = [
    'a' => ['b', 'c'],
    'd' => ['e', 'f' => [
        'g' => ['h', 'i']
    ]],
]

From that array i would like to find the content g, then the function should return the reference to this element or false if it does not find it. With the return of the function I can manipulate this array, adding, changing or deleting items.

1 answer

1


Yes, it is possible, you have to say in the name of the function that it is by reference, both in your statement and in the call:

function &ref(&$list) {
    $return = &$list[3] ?? false;
    return $return;
}
$list = ['a', 'b', 'c', 'd', 'e'];
$elemento = &ref($list);
$elemento = 'D';
echo $list[3]; // D

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I would try to do otherwise, most people do not understand the consequences of having something by reference, and almost always have better ways of solving the same problem. One of the great advantages is performance, but it’s what I always say, if you need PHP performance is not the proper language.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.