Is there a way in PHP to return a reference to an element in array?
function ref(&$array, &$ref) { $ref = $array[1]; }
$array = array(00, 11, 22, 33, 44, 55, 66, 77, 88, 99);
ref($array, $ref);
$ref = 'xxxxxxxxxx';
var_dump($ref);
var_dump($array);
I expect that $array will be changed as in the following code:
$array = array(00, 11, 22, 33, 44, 55, 66, 77, 88, 99);
$ref = &$array[1];
$ref = 'xxxxxxxxxx';
var_dump($ref);
var_dump($array);
Method 1: Using json_decode and json_encode method: The json_decode function accepts JSON encoded string and converts it into a PHP variable on the other hand json_encode returns a JSON encoded string for a given value. Syntax: $myArray = json_decode(json_encode($object), true);
With regards to your first question, the array is passed by reference UNLESS it is modified within the method / function you're calling. If you attempt to modify the array within the method / function, a copy of it is made first, and then only the copy is modified.
$this means the current object, the one the method is currently being run on. By returning $this a reference to the object the method is working gets sent back to the calling function.
Any type may be returned, including arrays and objects.
I've found two ways to return reference to an array element:
function & ref(&$array)
{
return $array[1];
}
$array = array(00, 11, 22, 33, 44, 55, 66, 77, 88, 99);
$ref =& ref($array);
$ref = 'xxxxxxxxx';
var_dump($ref);
var_dump($array);
function ref(&$array, &$ref = array())
{
$ref = array();
$ref[] = &$array[1];
}
$array = array(00, 11, 22, 33, 44, 55, 66, 77, 88, 99);
ref($array, $ref);
$ref[0] = 'xxxxxxxxx';
var_dump($ref);
var_dump($array);
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