Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach: "in" v. "as"

Tags:

foreach

php

What is the difference between these two usages of foreach?

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

foreach ($odp in $ftw) {
  //do more stuff
}
like image 313
Nick Heiner Avatar asked Aug 14 '09 01:08

Nick Heiner


2 Answers

First one is legal PHP, second one is not.

like image 117
Pavel Minaev Avatar answered Oct 03 '22 08:10

Pavel Minaev


Using in in PHP doesn't work. In Javascript however, a similar form is acceptable and they differ thusly:

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 give the value of the properties of the object, whereas for ... in ... (javascript) will give you the name of each property.

like image 38
nickf Avatar answered Oct 03 '22 10:10

nickf