2

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?

2 Answers 2

6

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

Comments

0

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 )
?>

Comments

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.