开发者

Understanding Arrays as part of the foreach in php

开发者 https://www.devze.com 2023-01-15 16:58 出处:网络
Having: $a as $key => $value; is the same as having: $a=array()开发者_StackOverflow; ?No, it\'s not. It\'s more like

Having:

$a as $key => $value;

is the same as having:

$a=array()开发者_StackOverflow;

?


No, it's not. It's more like

list($key, $value) = each($arr);

See the manual

foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}

is identical to

$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) {
    echo "Key: $key; Value: $value<br />\n";
}

Also see

  • The while Control Structure
  • list — Assign variables as if they were an array
  • each — Return the current key and value pair from an array and advance the array cursor
  • reset — Set the internal pointer of an array to its first element


First of all it has to say

foreach($a as $key => $value)

Then, as far as I know,

foreach($a = array())

doesn't compile.

That said, if you foreach, you iterate through the elements of an array. With the 'as' keyword, you get pairs of key/value for each element, where $key would be the index by which you can get $value:

$value = $a[$key];

Did this answer your question? If not, please specify.

edit:
In other programming languages it would spell something like

foreach($key => $value in $a)

or (C#)

foreach(KeyValuePair<type1, type2> kv in a)

which I think is more intuitive, but basically the same.


if you have the following:

$a = array('foo' => array('element1', 'element2'), 'bar' => array('sub1', 'sub2'));

if you use $a as $key=> $value in the foreach loop,

$key will be 'foo', and $value will be array('element1', 'element2') in the first iteration, in the second $key == 'bar' and $value == array('sub1', 'sub2').


If you loop over an array using foreach, the array is the first expression inside the parenthesis.

It can be a variable, like $a, or an array literal like array(1, 2, 3). The following loops are identical:

With an array literal:

foreach(array(1, 2, 3) as $number)
    print($number);

With a variable:

$a = array(1, 2, 3);
foreach($a as $number)
    print($number);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号