foreach($ vars as $ a => $ var){}是什么意思?

时间:2012-09-10 17:15:21

标签: php foreach

我遇到了这段代码foreach($vars as $a=>$var){ // some process here},我想知道使用foreach($vars as $var){ // some process here}时有什么区别?感谢。

4 个答案:

答案 0 :(得分:2)

运算符=>表示键和值之间的关系。你可以想象关键点=>到值。

修改

foreach可以通过两种方式使用:

  

1.迭代价值观:

每次循环循环时,变量都设置为数组中的下一个值。

例如:     

$fruitColours = array(
    "Banana" => "Yellow",
    "Apple"  => "Green",
    "Plum"   => "Purple",
);

foreach ($fruitColours as $colour)
{
    echo "$colour<br/>\n";
}

?>

以上将显示:

Yellow
Green
Purple

仅显示数组的值。

  

2.迭代键和值

每次循环时,变量都设置为下一个键和值对。

例如:     

$fruitColours = array(
    "Banana" => "Yellow",
    "Apple"  => "Green",
    "Plum"   => "Purple",
);

foreach ($fruitColours as $fruit => $colour)
{
    echo "$fruit is $colour<br/>\n";
}

?>

以上将显示:

Banana is Yellow
Apple is Green
Plum is Purple

检查php foreach documentation以获取进一步参考

答案 1 :(得分:2)

$vars = array(
  'key1'=>'something',
  'key2'=>'test',
);

foreach($vars as $key=>$value){
  echo "$key:$value" . PHP_EOL;
}

将输出:

key1:something
key2:test

答案 2 :(得分:1)

foreach($vars as $a=>$var){ // some process here} 迭代数组(在本例中为$vars)。在每次迭代中,$a归因于实际数组项的键,$var归因于相应的值。

foreach($vars as $var){ // some process here}与上面的相同,但是使用这个,只返回每个数组项的值。键值不会返回。

检查php手册中的this article以获取更多信息。

答案 3 :(得分:1)

不同之处在于foreach($vars as $var){ // some process here}只有foreach($vars as $a=>$var){ // some process here}才能获得价值,而使用 $data = array('NAME' => 'Tom', 'AGE' => 20); foreach($data as $var){ echo $var . "\n"; } echo "\n"; foreach($data as $key => $var){ echo $key .': '. $var . "\n"; } 时,您也会得到它的关键字。

Tom
20

NAME: Tom
AGE: 20

将输出

{{1}}