Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change global array values by changing the reference returned from a function

It's difficult to explain in word what I'm trying to do, so I'm providing a minimal example, see comments:

$g = array( 
    'a' => array(1, 2, 3), 
    'b' => array(4, 5, 6)
); // A global array

function &search($key) {
    global $g;
    return $g[$key];
}

$a = search('b'); // Now $a should be a reference to $g['b'], right?

$a[2] = 666;
print_r($a); // Ok changed
print_r($g); // Why not changed?

Tested on PHP 5.6.4.

Reason for what I'm trying to do is the fact the search function is obviously more complex in my use case (not just a key indexing!), and after the result has been found, it's handy to work on results: the original array is nested at various levels.

like image 317
lorenzo-s Avatar asked Feb 01 '26 23:02

lorenzo-s


1 Answers

From the manual:

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 for $myValue.

Your code just needs an extra ampersand (the reference "binding" one referred to above), as follows:

$a =& search('b');
like image 65
iainn Avatar answered Feb 04 '26 12:02

iainn