array:如何返回引用/指针

Hy everybody!

how to return an array reference / pointer in a function?

ex:

$a=array('given'=>array());

function getRef(&$ref){

//adds a child element to the given reference/pointer
$ref['test']=array();

//doesn't return the current reference/pointer
return $ref['test'];
}

//out: Array ( [given] => Array ( [test] => Array ( ) ) )
$p=getRef($a['given']);
print_r($a);

//out: same as above
//expected: ( [given] => Array ( [test] => Array ([test2] => Array ( ) ) ) )
$p['test2']=array();
print_r($a);

Thanks!

Maybe something like this:

$a=array('given'=>array());

function getRef(&$ref){

//adds a child element to the given reference/pointer
$ref['test']=array();

//doesn't return the current reference/pointer
return $ref['test'];
}

//out: Array ( [given] => Array ( [test] => Array ( ) ) )
$p=getRef($a['given']);
print_r($a);

//out: same as above
//expected: ( [given] => Array ( [test] => Array ([test2] => Array ( ) ) ) )
$p['given']['test']['test2']=array();
print_r($p);

Try this One

    <?php
$a=array('given'=>array());

function &getRef(&$ref){

//adds a child element to the given reference/pointer
$ref['test']=array();

//doesn't return the current reference/pointer
return $ref['test'];
}

//out: Array ( [given] => Array ( [test] => Array ( ) ) )
$p=&getRef($a['given']);
print_r($a);

//out: same as above
//expected: ( [given] => Array ( [test] => Array ([test2] => Array ( ) ) ) )
$p['test2']=array();
print_r($a);
?>

When you pass by reference you use the same variable inside the function as you do outside and you don't return a value. PHP Manual - Passing by Reference

$a = array('given' => array());

function getRef(&$a)
{
  $a['test']=array();   
}

// this now has the nested array test.
getRef($a['given']);
print_r($a);

If this is all your function is doing then I would advise to just set these nested arrays normally.

$b = ['given' => ['test' => ['test2' => []]]];
print_r($b);
function &getRef(&$ref){

return $ref['test'];

By using an ampersand at the start of a function, you return the refference of a varible instead of the value.