11

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);
3

1 Answer 1

27

I've found two ways to return reference to an array element:

1. Using return by reference and =&

    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);

2. Put reference into an 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);
Sign up to request clarification or add additional context in comments.

1 Comment

I chose the first method, and it worked. PHP is so strange that it passes strings by reference but arrays more or less by value (among many other peculiarities).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.