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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With