It was very difficult to come up with an informed title for this post.
Though PHP and JS are totally different languages, I am very surprised to find that altering an array passed into a function as an argument gives different results.
PHP
<?php
function thing($arr) {
$arr[2] = "WOOF";
}
$hello = array(1,2,3,4);
thing($hello);
print_r($hello);
// Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
?>
Javascript
function thing($arr) {
$arr[2] = "WOOF";
}
$hello = [1,2,3,4];
thing($hello);
console.log($hello);
// [1, 2, "WOOF", 4]
Which is "correct"?
Why is there a difference in results here? Why does JS accept that the argument is simply an alias to the original array, but PHP doesn't?
Which way is the most 'correct' -- and why?
In javascript object are passed by reference So you are getting the result like this so said that both the result are true in their own domain.
you can try this via console too..
>>> var s = [1,2,3,4];
undefined
>>> var b = s;
undefined
>>> b;
[1, 2, 3, 4]
>>> s;
[1, 2, 3, 4]
>>> b[2] = "data";
"data"
>>> b;
[1, 2, "data", 4]
>>> s;
[1, 2, "data", 4]
In php you give to function values of "$arr", and in JS - object "$arr"
<?php
function thing($arr) {
$arr[2] = "WOOF";
return ($arr);
}
$hello = array(1,2,3,4);
$hello=thing($hello);
print_r($hello);
// Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
?>