How does PHP 'foreach' actually work?

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

    PHP foreach loop can be used with Indexed arrays, Associative arrays and Object public variables.

    In foreach loop, the first thing php does is that it creates a copy of the array which is to be iterated over. PHP then iterates over this new copy of the array rather than the original one. This is demonstrated in the below example:

    ', print_r($numbers, true), '
    ', '
    '; foreach($numbers as $index => $number){ $numbers[$index] = $number + 1; # this is making changes to the origial array echo 'Inside of the array = ', $index, ': ', $number, '
    '; # showing data from the copied array } echo '
    ', '
    ', print_r($numbers, true), '
    '; # shows the original values (also includes the newly added values).

    Besides this, php does allow to use iterated values as a reference to the original array value as well. This is demonstrated below:

    ', print_r($numbers, true), '
    '; foreach($numbers as $index => &$number){ ++$number; # we are incrementing the original value echo 'Inside of the array = ', $index, ': ', $number, '
    '; # this is showing the original value } echo '
    '; echo '
    ', print_r($numbers, true), '
    '; # we are again showing the original value

    Note: It does not allow original array indexes to be used as references.

    Source: http://dwellupper.io/post/47/understanding-php-foreach-loop-with-examples

提交回复
热议问题