How does PHP 'foreach' actually work?

前端 未结 7 1388
温柔的废话
温柔的废话 2020-11-21 06:12

Let me prefix this by saying that I know what foreach is, does and how to use it. This question concerns how it works under the bonnet, and I don\'t want any an

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 06:23

    As per the documentation provided by PHP manual.

    On each iteration, the value of the current element is assigned to $v and the internal
    array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

    So as per your first example:

    $array = ['foo'=>1];
    foreach($array as $k=>&$v)
    {
       $array['bar']=2;
       echo($v);
    }
    

    $array have only single element, so as per the foreach execution, 1 assign to $v and it don't have any other element to move pointer

    But in your second example:

    $array = ['foo'=>1, 'bar'=>2];
    foreach($array as $k=>&$v)
    {
       $array['baz']=3;
       echo($v);
    }
    

    $array have two element, so now $array evaluate the zero indices and move the pointer by one. For first iteration of loop, added $array['baz']=3; as pass by reference.

提交回复
热议问题