0

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!

1
  • Check the below it works :) Commented Dec 17, 2015 at 20:24

4 Answers 4

1

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);
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Why should the OP "try this"? A good answer will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO.
1
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.

Comments

0

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

Comments

0

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

Comments

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.