Why can you push to an array refrence in JS but not PHP

Viewed 53

I came across this today and would like to know why it does this in terms of how arrays are treated in php and js.

JS

let x = [];
let i = x;

i.push('test');
console.log(x);
//prints ['test']

PHP

$x = [];
$i = $x;

array_push($i, 'test');
print_r($x);
/prints []
1 Answers

Well in JavaScript x is assigned by reference to i while in PHP it is by value. If you want to make it work in PHP you should use:

$i = &$x;

Which means any changes in $i will affect $x. See PHP: References

Related