How does PHP 'foreach' actually work?
Foreach in PHP supports iteration over three types of values: arrays, normal objects, and traversable objects.
Array and Object Iteration:
For arrays and objects, the iteration mechanism is more complex. PHP arrays are actually ordered dictionaries that are traversed according to the insertion order. Iterating over plain objects is similar to iterating over arrays because object properties are also stored as a dictionary.
During iteration, the internal array pointer is not directly used. Instead, a HashPointer is employed to keep track of the current element. After the loop body runs, the HashPointer will be restored, but only if the element still exists. Otherwise, the current array pointer will be used.
If the array is not a reference and has a reference count greater than 1, it is duplicated before iteration. This duplication is done to prevent IAP changes from leaking to the original array.
Modification During Iteration:
PHP allows modifications during iteration, which can lead to some confusing behavior. If an element is removed during iteration, the HashPointer will be advanced to the next element only if the HashPointer backup/restore mechanism succeeds. If it fails, the current array pointer (which is at the end of the array) will be used instead.
Nested loops can also affect the behavior of foreach. If the current element of the outer loop is removed, the outer loop will stop after the first iteration because the HashPointer will fail to restore.
PHP 7 Changes:
PHP 7 introduced several changes to foreach iteration:
The above is the detailed content of How Does PHP's `foreach` Loop Actually Work Under the Hood?. For more information, please follow other related articles on the PHP Chinese website!