简体   繁体   English

foreach:“in”v。“as”

[英]foreach: “in” v. “as”

What is the difference between these two usages of foreach? 这两种foreach用法有什么区别?

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

foreach ($odp in $ftw) {
  //do more stuff
}

第一个是合法的PHP,第二个不是

Using in in PHP doesn't work. 在PHP中使用in不起作用。 In Javascript however, a similar form is acceptable and they differ thusly: 但是,在Javascript中,类似的形式是可以接受的,因此它们不同:

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. 基本上, for each ... in ... (Javascript)或foreach ... as ... (PHP)将给出对象属性的值,而for ... in ... (javascript)将给你每个属性的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM