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?

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

1 Comment

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. :(

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.