PHP foreach 中“as $key => $value”和“as $value”的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18492784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between "as $key => $value" and "as $value" in PHP foreach
提问by handmdmr
I have a database call and I'm trying to figure out what the $key => $value
does in a foreach
loop.
我有一个数据库调用,我试图找出什么$key => $value
做的一个foreach
循环。
The reason I ask is because both these codes output the same thing, so I'm trying to understand why it's written this way. Here's the code:
我问的原因是因为这两个代码输出相同的东西,所以我试图理解为什么它是这样写的。这是代码:
1)In foreach use $key => $value
1)在foreach中使用 $key => $value
foreach($featured as $key => $value){
echo $value['name'];
}
this outputs the same as:
这输出与:
2)In foreach use only $value
2)仅在 foreach 中使用 $value
foreach($featured as $value) {
echo $value['name'];
}
So my question is, what is the difference between $key => $value
or just $value
in the foreach
loop. The array is multidimensional if that makes a difference, I just want to know why to pass $key
to $value
in the foreach
loop.
所以我的问题是,是什么样的区别$key => $value
,或只是$value
在foreach
循环。如果这有所不同,该数组是多维的,我只想知道为什么$key
要$value
在foreach
循环中传递给。
回答by djiango
Well, the $key => $value
in the foreach loop refers to the key-value pairs in associative arrays, where the key serves as the index to determine the value instead of a number like 0,1,2,... In PHP, associative arrays look like this:
好吧,$key => $value
foreach 循环中的 指的是关联数组中的键值对,其中键作为索引来确定值而不是像 0,1,2 之类的数字,...在 PHP 中,关联数组看起来像这个:
$featured = array('key1' => 'value1', 'key2' => 'value2', etc.);
In the PHP code: $featured
is the associative array being looped through, and as $key => $value
means that each time the loop runs and selects a key-value pair from the array, it stores the key in the local $key
variable to use inside the loop block and the value in the local $value
variable. So for our example array above, the foreach loop would reach the first key-value pair, and if you specified as $key => $value
, it would store 'key1'
in the $key
variable and 'value1'
in the $value
variable.
在 PHP 代码中:$featured
是循环通过的关联数组,as $key => $value
意味着每次循环运行并从数组中选择一个键值对时,它会将键存储在局部$key
变量中以在循环块内部使用,并且在局部$value
变量。因此,对于我们上面的例子阵列,foreach循环将达到第一个键值对,如果你指定的as $key => $value
,它会存储'key1'
在$key
变量,'value1'
在$value
变量。
Since you don't use the $key
variable inside your loop block, adding it or removing it doesn't change the output of the loop, but it's best to include the key-value pair to show that it's an associative array.
由于您不在$key
循环块内使用该变量,因此添加或删除它不会改变循环的输出,但最好包含键值对以表明它是一个关联数组。
Also note that the as $key => $value
designation is arbitrary. You could replace that with as $foo => $bar
and it would work fine as long as you changed the variable references inside the loop block to the new variables, $foo
and $bar
. But making them $key
and $value
helps to keep track of what they mean.
另请注意,as $key => $value
指定是任意的。您可以将其替换as $foo => $bar
为,只要您将循环块内的变量引用更改为新变量,它就可以正常工作,$foo
并且$bar
. 但是制作它们$key
并$value
有助于跟踪它们的含义。
回答by Charaf JRA
Let's say you have an associative array like this:
假设您有一个像这样的关联数组:
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => array('x'=>123)
);
In the first iteration : $key="one"
and $value=1
.
在第一次迭代中: $key="one"
和$value=1
。
Sometimes you need this key ,if you want only the value , you can avoid using it.
有时你需要这个键,如果你只想要值,你可以避免使用它。
In the last iteration : $key='seventeen'
and $value = array('x'=>123)
so to get value of the first element in this array
value, you need a key
, x in this case: $value['x'] =123
.
在最后一次迭代 : 中$key='seventeen'
,$value = array('x'=>123)
要获取此值中第一个元素的array
值,key
在这种情况下,您需要 a , x: $value['x'] =123
。
回答by Ahmad Baktash Hayeri
A very important place where it is REQUIREDto use the key => value
pair in foreach
loop is to be mentioned. Suppose you would want to add a new/sub-element to an existing item (in another key) in the $features
array. You should do the following:
需要提到一个非常重要的地方,它需要key => value
在foreach
循环中使用对。假设您想向数组中的现有项目(在另一个键中)添加一个新/子元素。您应该执行以下操作:$features
foreach($features as $key => $feature) {
$features[$key]['new_key'] = 'new value';
}
Instead of this:
取而代之的是:
foreach($features as $feature) {
$feature['new_key'] = 'new value';
}
The bigdifference here is that, in the first case you are accessing the array's sub-value via the main array itself with a keyto the element which is currently being pointed to by the array pointer.
这里的最大区别在于,在第一种情况下,您通过主数组本身访问数组的子值,并使用指向当前由数组指针指向的元素的键。
While in the second (which doesn't work for this purpose) you are assigning the sub-value in the array to a temporary variable $feature
which is unset after each loop iteration.
在第二个(不适用于此目的)中,您将数组中的子值分配给一个临时变量$feature
,该变量在每次循环迭代后都未设置。
回答by sargas
The difference is that on the
不同的是,在
foreach($featured as $key => $value){
echo $value['name'];
}
you are able to manipulate the value of each iteration's $key
from their key-value pair. Like @djiango answered, if you are not manipulating each value's $key
, the result of the loop will be exactly the same as
您可以$key
从它们的键值对中操作每个迭代的值。就像@djiango 回答的那样,如果您不操作每个值的$key
,则循环的结果将与
foreach($featured as $value) {
echo $value['name']
}
Source:You can read it from the PHP Documentation:
来源:您可以从PHP 文档中阅读:
The first form loops over the array given by array_expression. On each iteration, the value >of the current element is assigned to $value and the internal array pointer is advanced by >one (so on the next iteration, you'll be looking at the next element).*
The second form will additionally assign the current element's key to the $key variable on >each iteration.
第一种形式循环遍历由 array_expression 给出的数组。在每次迭代中,当前元素的值 > 被分配给 $value 并且内部数组指针前移 >one(因此在下一次迭代中,您将查看下一个元素)。*
第二种形式将在每次迭代时额外将当前元素的键分配给 $key 变量。
If the data you are manipulating is, say, arrays with custom keys, you could print them to screen like so:
如果您操作的数据是带有自定义键的数组,您可以将它们打印到屏幕上,如下所示:
$array = ("name" => "Paul", "age" => 23);
$array = ("name" => "Paul", "age" => 23);
foreach($featured as $key => $value){
echo $key . "->" . $value;
}
Should print:
应该打印:
name->Paul
name->Paul
age->23
age->23
And you wouldn't be able to do that with a foreach($featured as $value)
with the same ease. So consider the format above a convenient way to manipulate keys when needed.
而且您将无法轻松地做到这一点foreach($featured as $value)
。因此,将上述格式视为一种在需要时操作键的便捷方式。
Cheers
干杯
回答by aynber
Say you have an array like this:
假设你有一个这样的数组:
$array = (0=>'123',1=>'abc','test'=>'hi there!')
In your foreach loop, each loop would be:
在您的 foreach 循环中,每个循环将是:
$key = 0, $value = '123'
$key = 1, $value = 'abc'
$key = 'test', $value = 'hi there!'
It's great for those times when you need to know the array key.
当您需要知道数组键时,这非常有用。
回答by 3seconds
if the array looks like:
如果数组看起来像:
- $featured["fruit"] = "orange";
- $featured["fruit"] = "banana";
- $featured["vegetable"] = "carrot";
- $featured["fruit"] = "orange";
- $featured["fruit"] = "banana";
- $featured["vegetable"] = "carrot";
the $key will hold the type (fruit or vegetable) for each array value (orange, banana or carrot)
$key 将保存每个数组值(橙色、香蕉或胡萝卜)的类型(水果或蔬菜)
回答by Thomas Martin Klein
here $keywill contain the $keyassociated with $valuein $featured. The difference is that now you have that key.
这里$键将包含$键关联$值的功能$。不同之处在于,现在您拥有了那把钥匙。
array("thekey"=>array("name"=>"joe"))
here $valueis
这里$value是
array("name"=>"joe")
$keyis "thekey"
$key是“thekey”
回答by optimiertes
Sample Array: Left ones are the keys, right one are my values
示例数组:左边是键,右边是我的值
$array = array(
'key-1' => 'value-1',
'key-2' => 'value-2',
'key-3' => 'value-3',
);
Example A: I want only the values of $array
示例 A:我只想要 $array
foreach($array as $value) {
echo $value; // Through $value I get first access to 'value-1' then 'value-2' and to 'value-3'
}
Example B: I want each value AND key of $array
示例 B:我想要的每个值 AND 键 $array
foreach($array as $key => $value) {
echo $value; // Through $value I get first access to 'value-1' then 'value-2' and to 'value-3'
echo $key; // Through $key I get access to 'key-1' then 'key-2' and finally 'key-3'
echo $array[$key]; // Accessing the value through $key = Same output as echo $value;
$array[$key] = $value + 1; // Exmaple usage of $key: Change the value by increasing it by 1
}