Introduction:
foreach is used extensively in PHP for looping through arrays, objects, and other data structures. Understanding its inner workings is crucial to avoid unexpected behavior.
Three Types of foreach Iterables:
foreach supports three types of iterables:
Traversable Object Iteration:
For Traversable objects, foreach acts as syntactical sugar for:
foreach ($it as $k => $v) {} translates to: if ($it instanceof IteratorAggregate) { $it = $it->getIterator(); } for ($it->rewind(); $it->valid(); $it->next()) { $v = $it->current(); $k = $it->key(); // ... }
Array and Object Iteration:
Ordered Dictionaries:
PHP arrays and objects are essentially ordered dictionaries that maintain the order of insertion. Iteration follows this order.
Conversion of Objects:
Packed object representations are converted to dictionaries during iteration. Plain-object iteration thus becomes similar to array iteration.
Internal Array Pointer (IAP):
Arrays in PHP 5 have an internal array pointer (IAP) that supports modifications and skipping over removed elements.
HashPointer:
foreach in PHP 5 uses a HashPointer to back up the IAP position and hash before running the loop body. It restores it afterward if the element still exists; otherwise, it uses the current IAP position.
Array Duplication:
foreach in PHP 5 duplicates arrays that are not references (is_ref=0) and have a refcount greater than 1.
PHP 5 Examples:
PHP 7 Changes:
Hashtable Iterators:
PHP 7 uses external hashtable iterators, registered in the array. Each iterator is advanced if the corresponding element is removed.
No IAP Usage by foreach:
foreach no longer uses the IAP, eliminating the need for duplication. By-value array iteration always uses the original elements.
Array Duplication:
Arrays are no longer duplicated during by-value iteration, regardless of their refcount or reference status.
PHP 7 Examples:
Additional PHP 7 Enhancements:
The above is the detailed content of How Does PHP's `foreach` Loop Actually Work, and How Has Its Implementation Changed Between PHP 5 and PHP 7?. For more information, please follow other related articles on the PHP Chinese website!