0

In the Javascript code:

var people = [{name:"john",age:20},{name:"bob",age:30},{name:"kate",age:40}];

people.forEach(function(person,i){
person.isHuman = true;
})

console.log(people) would give

[{name:"john",age:20,isHuman:true},{name:"bob",age:30,isHuman:true},{name:"kate",age:40,isHuman:true}]

However, the same code in PHP

$people = [["name"=>"john","age"=>20],["name"=>"bob","age"=>30],["name"=>"kate","age"=>40]];

foreach($people as $i=>$person){
$person['isHuman']=true;
}

var_dump($people) would give

[["name"=>"john","age"=>20],["name"=>"bob","age"=>30],["name"=>"kate","age"=>40]]

The new "isHuman" property is not added to the original array of objects.

In the PHP case, I know you can do "$people[$i]['isHuman']=true" to alter the object in the original array. But is there a way to do "$person['isHuman']=true" and have that change reflected in the original array?

And my second question is why/for what reasons is this behavior different between Javascript and PHP?

praine
  • 405
  • 1
  • 3
  • 14
  • I would do this `foreach($people as $i=>&$person){ $person['isHuman']=true; }` note the `&` which is by reference. It's not really different. In JS it on by default, basically. Further, arrays are technically objects in JS (prototype language) and in PHP objects are pass by reference automatically, but an array is not an object in PHP. – ArtisticPhoenix Feb 05 '19 at 08:40
  • see also this post on what an array is in JS https://stackoverflow.com/questions/5048371/are-javascript-arrays-primitives-strings-objects – ArtisticPhoenix Feb 05 '19 at 08:46

0 Answers0