2

I am trying to run following code:

$a = array('aa');
function my_func (& $m) {
 return $m;
}
$c = & my_func($a);
$c[] = 'bb';
var_dump($a);
echo '--------';
var_dump($c);

My expectation were that $a and $c would have same reference. But the result is different.

Result i got was:

array(1) { [0]=> string(2) "aa" } --------array(2) { [0]=> string(2) "aa" [1]=> string(2) "bb" } 

What is wrong in above piece of code?

George Cummins
29k8 gold badges74 silver badges91 bronze badges
asked Nov 15, 2011 at 18:54

1 Answer 1

4

I think what you are looking for is function returning by reference (this in conjunction with passing by reference in your example).

Here is an example:

function &my_func(&$m) {
 return $m;
}
$a = array('aa');
$c = &my_func($a);
$c[] = 'bb';
var_dump($a);
echo "---\n";
var_dump($c);

Outputs:

array(2) {
 [0]=>
 string(2) "aa"
 [1]=>
 string(2) "bb"
}
---
array(2) {
 [0]=>
 string(2) "aa"
 [1]=>
 string(2) "bb"
}
answered Nov 15, 2011 at 19:05
1
  • I dint know about returning by reference in php. Thanks. Coming from a non-php background, this is really different for me. And i fear, i dont introduce some unintentional bugs. :( Commented Nov 15, 2011 at 19:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.