Daniel Trebbien
Daniel Trebbien

Reputation: 39208

Why does this shorter way of calling a PHP function with an array reference lead to a different result?

If a function my_func is defined as:

function my_func(&$arr) {
    array_push($arr, 0);
    array_push($arr, 1);
    array_push($arr, 2);
    array_push($arr, 3);
    array_push($arr, 4);
}

If I call my_func as follows, then the results are as expected:

$test_array = array();
my_func($test_array);
print_r($test_array);

Results in:

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
)

I was thinking that I could shorten this code somewhat by calling my_func as follows:

my_func($test_array = array());
print_r($test_array);

However, the result changes:

Array
(
)

Why does this shorter code snippet lead to a different result?

Upvotes: 2

Views: 87

Answers (1)

phant0m
phant0m

Reputation: 16905

You're not passing the variable by reference, but the value of an expression.

If you were to enable all errors, you would see the following message:

Strict Standards: Only variables should be passed by reference in 

The value of an assignment is the value that is being assigned itself. It is that value—a copy of the array—that gets passed to my_func.

The PHP documentation on the matter puts this more strongly:

No other expressions should be passed by reference, as the result is undefined.

Conclusion: Only ever pass variables ($x, $x[0], $x->a), new objects or references returned from functions to a function expecting a reference.

Upvotes: 5

Related Questions