Foreach: "in" v. "as"

What is the difference between these two foreach customs?

foreach ($nodes as $node) {
 //do stuff
}

foreach ($odp in $ftw) {
  //do more stuff
}
+5
source share
2 answers

The first is legal PHP, the second is not .

+13
source

Usage inin PHP does not work. However, in Javascript, a similar form is acceptable, and they differ:

var obj = {
    'a' : 'Apple',
    'b' : 'Banana',
    'c' : 'Carrot'
};

for (var i in obj) {
    alert(i); // "a", "b", "c"
}

for each (var i in obj) {
    alert(i); // "Apple", "Banana", "Carrot"
}

basically, for each ... in ...(Javascript) or foreach ... as ...(PHP) will return the value of the properties of the object, while for ... in ...(javascript) will give you the name of each property.

+7
source

All Articles