How does PHP 'foreach' actually work?

前端 未结 7 1406
温柔的废话
温柔的废话 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:47

    Some points to note when working with foreach():

    a) foreach works on the prospected copy of the original array. It means foreach() will have SHARED data storage until or unless a prospected copy is not created foreach Notes/User comments.

    b) What triggers a prospected copy? A prospected copy is created based on the policy of copy-on-write, that is, whenever an array passed to foreach() is changed, a clone of the original array is created.

    c) The original array and foreach() iterator will have DISTINCT SENTINEL VARIABLES, that is, one for the original array and other for foreach; see the test code below. SPL , Iterators, and Array Iterator.

    Stack Overflow question How to make sure the value is reset in a 'foreach' loop in PHP? addresses the cases (3,4,5) of your question.

    The following example shows that each() and reset() DOES NOT affect SENTINEL variables (for example, the current index variable) of the foreach() iterator.

    $array = array(1, 2, 3, 4, 5);
    
    list($key2, $val2) = each($array);
    echo "each() Original (outside): $key2 => $val2<br/>";
    
    foreach($array as $key => $val){
        echo "foreach: $key => $val<br/>";
    
        list($key2,$val2) = each($array);
        echo "each() Original(inside): $key2 => $val2<br/>";
    
        echo "--------Iteration--------<br/>";
        if ($key == 3){
            echo "Resetting original array pointer<br/>";
            reset($array);
        }
    }
    
    list($key2, $val2) = each($array);
    echo "each() Original (outside): $key2 => $val2<br/>";
    

    Output:

    each() Original (outside): 0 => 1
    foreach: 0 => 1
    each() Original(inside): 1 => 2
    --------Iteration--------
    foreach: 1 => 2
    each() Original(inside): 2 => 3
    --------Iteration--------
    foreach: 2 => 3
    each() Original(inside): 3 => 4
    --------Iteration--------
    foreach: 3 => 4
    each() Original(inside): 4 => 5
    --------Iteration--------
    Resetting original array pointer
    foreach: 4 => 5
    each() Original(inside): 0=>1
    --------Iteration--------
    each() Original (outside): 1 => 2
    
    0 讨论(0)
提交回复
热议问题