PHP:返回对数组元素的引用

时间:2014-04-10 10:04:50

标签: php arrays

PHP中有没有办法返回对数组中元素的引用?

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

我希望$ array会被改变,如下面的代码所示:

$array = array(00, 11, 22, 33, 44, 55, 66, 77, 88, 99);
$ref = &$array[1];
$ref = 'xxxxxxxxxx';
var_dump($ref);
var_dump($array);

1 个答案:

答案 0 :(得分:14)

我找到了两种方法来返回对数组元素的引用:

1。使用参考返回和=&

    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。将引用放入数组

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