Robel Tech 🚀

How does PHP foreach actually work

February 20, 2025

How does PHP foreach actually work

Looping done arrays oregon objects is a cardinal facet of programming, and PHP presents a almighty implement for this: the foreach loop. Knowing however foreach plant nether the hood tin importantly better your coding ratio and aid you debar sudden behaviour. This article delves into the mechanics of PHP’s foreach loop, exploring its inner workings and offering applicable examples to solidify your knowing. We’ll screen every little thing from basal iteration to dealing with multi-dimensional arrays and objects, equipping you with the cognition to leverage foreach efficaciously successful your tasks.

Iterating Complete Arrays

The easiest usage lawsuit for foreach is iterating complete arrays. PHP’s foreach doesn’t make a transcript of the array; it straight plant with the first. This is important for show, particularly with ample datasets. foreach provides 2 syntax variations: 1 for accessing conscionable the values, and different for accessing some keys and values.

For illustration:

$colours = ['reddish', 'greenish', 'bluish']; foreach ($colours arsenic $colour) { echo $colour . ' '; } // Output: reddish greenish bluish 

And for accessing some cardinal and worth:

$information = ['sanction' => 'John', 'property' => 30]; foreach ($information arsenic $cardinal => $worth) { echo $cardinal . ': ' . $worth . '<br></br>'; } // Output: sanction: John // property: 30 

Inner Pointer Manipulation

foreach maintains an inner pointer to the actual component successful the array. With all iteration, this pointer is robotically precocious. Importantly, modifying the array’s inner pointer inside the loop tin pb to unpredictable outcomes. It’s mostly champion pattern to debar straight manipulating the array inside a foreach loop until you person a circumstantial ground to bash truthful.

See this illustration demonstrating the computerized pointer development:

$numbers = [1, 2, three, four, 5]; foreach ($numbers arsenic $figure) { echo $figure  2 . ' '; } // Output: 2 four 6 eight 10 

Iterating Complete Objects

foreach isn’t constricted to arrays; it tin besides iterate complete objects. Once utilized with objects, foreach accesses the national properties of the entity. This gives a handy manner to loop done and manipulate entity information. Fto’s exemplify with a elemental people:

people Person { national $sanction = 'Jane Doe'; national $e-mail = 'jane.doe@illustration.com'; } $person = fresh Person(); foreach ($person arsenic $place => $worth) { echo $place . ': ' . $worth . '<br></br>'; } // Output: sanction: Jane Doe // electronic mail: jane.doe@illustration.com 

Multi-Dimensional Arrays and Nested Loops

Dealing with multi-dimensional arrays with foreach frequently entails nested loops. All flat of nesting corresponds to a magnitude of the array. This permits you to procedure all component inside the nested arrays efficaciously. Present’s however you tin navigate a 2-dimensional array:

$matrix = [[1, 2], [three, four]]; foreach ($matrix arsenic $line) { foreach ($line arsenic $component) { echo $component . ' '; } echo '<br></br>'; } // Output: 1 2 // three four 

Cardinal Benefits of Utilizing foreach

  • Readability: foreach affords cleaner syntax in contrast to conventional for loops once running with arrays and objects.
  • Ratio: It’s mostly much businesslike for traversing arrays and objects, particularly ample ones.

Communal Pitfalls to Debar

  1. Modifying the Array Inside the Loop: Arsenic talked about earlier, straight altering the array’s construction inside the loop tin pb to surprising behaviour.
  2. Undefined Variables: Ever guarantee the array oregon entity you’re iterating complete is outlined to forestall errors.

Champion Practices for Utilizing foreach

  • Usage the cardinal-worth syntax once you demand entree to some keys and values.
  • Debar modifying the array’s construction inside the loop until essential.

Infographic Placeholder: [Insert infographic illustrating the inner workings of foreach with an array and an entity]

Arsenic we’ve seen, the foreach loop is a versatile and almighty implement successful PHP. By knowing its interior workings, you tin compose cleaner, much businesslike, and predictable codification. Leveraging the cardinal-worth syntax, dealing with multi-dimensional arrays, and avoiding communal pitfalls volition change you to maximize the advantages of foreach successful your PHP tasks. Research additional by diving into the authoritative PHP documentation and experimenting with antithetic situations. Larn much astir precocious looping methods present. For much successful-extent accusation connected PHP loops, cheque retired this assets connected PHP foreach loops. You tin besides research antithetic loop varieties successful PHP present and larn much astir array iteration present.

FAQ

Q: What occurs if I modify the array inside a foreach loop?

A: Modifying the array’s construction (including oregon eradicating components) inside a foreach loop tin pb to unpredictable outcomes and is mostly discouraged except you person a circumstantial ground and realize the implications.

Question & Answer :
Fto maine prefix this by saying that I cognize what foreach is, does and however to usage it. This motion issues however it plant nether the bonnet, and I don’t privation immoderate solutions on the traces of “this is however you loop an array with foreach”.


For a agelong clip I assumed that foreach labored with the array itself. Past I recovered galore references to the information that it plant with a transcript of the array, and I person since assumed this to beryllium the extremity of the narrative. However I late obtained into a treatment connected the substance, and last a small experimentation recovered that this was not successful information a hundred% actual.

Fto maine entertainment what I average. For the pursuing trial instances, we volition beryllium running with the pursuing array:

$array = array(1, 2, three, four, 5); 

Trial lawsuit 1:

foreach ($array arsenic $point) { echo "$point\n"; $array[] = $point; } print_r($array); /* Output successful loop: 1 2 three four 5 $array last loop: 1 2 three four 5 1 2 three four 5 */ 

This intelligibly exhibits that we are not running straight with the origin array - other the loop would proceed everlastingly, since we are perpetually pushing gadgets onto the array throughout the loop. However conscionable to beryllium certain this is the lawsuit:

Trial lawsuit 2:

foreach ($array arsenic $cardinal => $point) { $array[$cardinal + 1] = $point + 2; echo "$point\n"; } print_r($array); /* Output successful loop: 1 2 three four 5 $array last loop: 1 three four 5 6 7 */ 

This backs ahead our first decision, we are running with a transcript of the origin array throughout the loop, other we would seat the modified values throughout the loop. However…

If we expression successful the handbook, we discovery this message:

Once foreach archetypal begins executing, the inner array pointer is routinely reset to the archetypal component of the array.

Correct… this appears to propose that foreach depends connected the array pointer of the origin array. However we’ve conscionable proved that we’re not running with the origin array, correct? Fine, not wholly.

Trial lawsuit three:

// Decision the array pointer connected 1 to brand certain it doesn't impact the loop var_dump(all($array)); foreach ($array arsenic $point) { echo "$point\n"; } var_dump(all($array)); /* Output array(four) { [1]=> int(1) ["worth"]=> int(1) [zero]=> int(zero) ["cardinal"]=> int(zero) } 1 2 three four 5 bool(mendacious) */ 

Truthful, contempt the information that we are not running straight with the origin array, we are running straight with the origin array pointer - the information that the pointer is astatine the extremity of the array astatine the extremity of the loop exhibits this. But this tin’t beryllium actual - if it was, past trial lawsuit 1 would loop everlastingly.

The PHP handbook besides states:

Arsenic foreach depends connected the inner array pointer altering it inside the loop whitethorn pb to surprising behaviour.

Fine, fto’s discovery retired what that “sudden behaviour” is (technically, immoderate behaviour is surprising since I nary longer cognize what to anticipate).

Trial lawsuit four:

foreach ($array arsenic $cardinal => $point) { echo "$point\n"; all($array); } /* Output: 1 2 three four 5 */ 

Trial lawsuit 5:

foreach ($array arsenic $cardinal => $point) { echo "$point\n"; reset($array); } /* Output: 1 2 three four 5 */ 

…thing that surprising location, successful information it appears to activity the “transcript of origin” explanation.


The Motion

What is going connected present? My C-fu is not bully adequate for maine to capable to extract a appropriate decision merely by trying astatine the PHP origin codification, I would acknowledge it if person may interpret it into Nation for maine.

It appears to maine that foreach plant with a transcript of the array, however units the array pointer of the origin array to the extremity of the array last the loop.

  • Is this accurate and the entire narrative?
  • If not, what is it truly doing?
  • Is location immoderate occupation wherever utilizing capabilities that set the array pointer (all(), reset() et al.) throughout a foreach may impact the result of the loop?

foreach helps iteration complete 3 antithetic sorts of values:

Successful the pursuing, I volition attempt to explicate exactly however iteration plant successful antithetic instances. By cold the easiest lawsuit is Traversable objects, arsenic for these foreach is basically lone syntax sweetener for codification on these traces:

foreach ($it arsenic $okay => $v) { /* ... */ } /* interprets to: */ if ($it instanceof IteratorAggregate) { $it = $it->getIterator(); } for ($it->rewind(); $it->legitimate(); $it->adjacent()) { $v = $it->actual(); $okay = $it->cardinal(); /* ... */ } 

For inner courses, existent methodology calls are averted by utilizing an inner API that basically conscionable mirrors the Iterator interface connected the C flat.

Iteration of arrays and plain objects is importantly much complex. Archetypal of each, it ought to beryllium famous that successful PHP “arrays” are truly ordered dictionaries and they volition beryllium traversed in accordance to this command (which matches the insertion command arsenic agelong arsenic you didn’t usage thing similar kind). This is opposed to iterating by the earthy command of the keys (however lists successful another languages frequently activity) oregon having nary outlined command astatine each (however dictionaries successful another languages frequently activity).

The aforesaid besides applies to objects, arsenic the entity properties tin beryllium seen arsenic different (ordered) dictionary mapping place names to their values, positive any visibility dealing with. Successful the bulk of instances, the entity properties are not really saved successful this instead inefficient manner. Nevertheless, if you commencement iterating complete an entity, the packed cooperation that is usually utilized volition beryllium transformed to a existent dictionary. Astatine that component, iteration of plain objects turns into precise akin to iteration of arrays (which is wherefore I’m not discussing plain-entity iteration overmuch successful present).

Truthful cold, truthful bully. Iterating complete a dictionary tin’t beryllium excessively difficult, correct? The issues statesman once you recognize that an array/entity tin alteration throughout iteration. Location are aggregate methods this tin hap:

  • If you iterate by mention utilizing foreach ($arr arsenic &$v) past $arr is turned into a mention and you tin alteration it throughout iteration.
  • Successful PHP 5 the aforesaid applies equal if you iterate by worth, however the array was a mention beforehand: $ref =& $arr; foreach ($ref arsenic $v)
  • Objects person by-grip passing semantics, which for about applicable functions means that they behave similar references. Truthful objects tin ever beryllium modified throughout iteration.

The job with permitting modifications throughout iteration is the lawsuit wherever the component you are presently connected is eliminated. Opportunity you usage a pointer to support path of which array component you are presently astatine. If this component is present freed, you are near with a dangling pointer (normally ensuing successful a segfault).

Location are antithetic methods of fixing this content. PHP 5 and PHP 7 disagree importantly successful this respect and I’ll depict some behaviors successful the pursuing. The abstract is that PHP 5’s attack was instead dumb and pb to each sorts of bizarre border-lawsuit points, piece PHP 7’s much active attack outcomes successful much predictable and accordant behaviour.

Arsenic a past preliminary, it ought to beryllium famous that PHP makes use of mention counting and transcript-connected-compose to negociate representation. This means that if you “transcript” a worth, you really conscionable reuse the aged worth and increment its mention number (refcount). Lone erstwhile you execute any benignant of modification a existent transcript (known as a “duplication”) volition beryllium carried out. Seat You’re being lied to for a much extended instauration connected this subject.

PHP 5

Inner array pointer and HashPointer

Arrays successful PHP 5 person 1 devoted “inner array pointer” (IAP), which decently helps modifications: At any time when an component is eliminated, location volition beryllium a cheque whether or not the IAP factors to this component. If it does, it is precocious to the adjacent component alternatively.

Piece foreach does brand usage of the IAP, location is an further complication: Location is lone 1 IAP, however 1 array tin beryllium portion of aggregate foreach loops:

// Utilizing by-ref iteration present to brand certain that it's truly // the aforesaid array successful some loops and not a transcript foreach ($arr arsenic &$v1) { foreach ($arr arsenic &$v) { // ... } } 

To activity 2 simultaneous loops with lone 1 inner array pointer, foreach performs the pursuing shenanigans: Earlier the loop assemblage is executed, foreach volition backmost ahead a pointer to the actual component and its hash into a per-foreach HashPointer. Last the loop assemblage runs, the IAP volition beryllium fit backmost to this component if it inactive exists. If nevertheless the component has been eliminated, we’ll conscionable usage wherever the IAP is presently astatine. This strategy largely-kinda-kind of plant, however location’s a batch of bizarre behaviour you tin acquire retired of it, any of which I’ll show beneath.

Array duplication

The IAP is a available characteristic of an array (uncovered done the actual household of features), arsenic specified modifications to the IAP number arsenic modifications nether transcript-connected-compose semantics. This, unluckily, means that foreach is successful galore instances compelled to duplicate the array it is iterating complete. The exact circumstances are:

  1. The array is not a mention (is_ref=zero). If it’s a mention, past adjustments to it are expected to propagate, truthful it ought to not beryllium duplicated.
  2. The array has refcount>1. If refcount is 1, past the array is not shared and we’re escaped to modify it straight.

If the array is not duplicated (is_ref=zero, refcount=1), past lone its refcount volition beryllium incremented (*). Moreover, if foreach by mention is utilized, past the (possibly duplicated) array volition beryllium turned into a mention.

See this codification arsenic an illustration wherever duplication happens:

relation iterate($arr) { foreach ($arr arsenic $v) {} } $outerArr = [zero, 1, 2, three, four]; iterate($outerArr); 

Present, $arr volition beryllium duplicated to forestall IAP modifications connected $arr from leaking to $outerArr. Successful status of the situations supra, the array is not a mention (is_ref=zero) and is utilized successful 2 locations (refcount=2). This demand is unlucky and an artifact of the suboptimal implementation (location is nary interest of modification throughout iteration present, truthful we don’t truly demand to usage the IAP successful the archetypal spot).

(*) Incrementing the refcount present sounds innocuous, however violates transcript-connected-compose (Cattle) semantics: This means that we are going to modify the IAP of a refcount=2 array, piece Cattle dictates that modifications tin lone beryllium carried out connected refcount=1 values. This usurpation outcomes successful person-available behaviour alteration (piece a Cattle is usually clear) due to the fact that the IAP alteration connected the iterated array volition beryllium observable – however lone till the archetypal non-IAP modification connected the array. Alternatively, the 3 “legitimate” choices would person been a) to ever duplicate, b) bash not increment the refcount and frankincense permitting the iterated array to beryllium arbitrarily modified successful the loop oregon c) don’t usage the IAP astatine each (the PHP 7 resolution).

Assumption development command

Location is 1 past implementation item that you person to beryllium alert of to decently realize the codification samples beneath. The “average” manner of looping done any information construction would expression thing similar this successful pseudocode:

reset(arr); piece (get_current_data(arr, &information) == Occurrence) { codification(); move_forward(arr); } 

Nevertheless foreach, being a instead particular snowflake, chooses to bash issues somewhat otherwise:

reset(arr); piece (get_current_data(arr, &information) == Occurrence) { move_forward(arr); codification(); } 

Particularly, the array pointer is already moved guardant earlier the loop assemblage runs. This means that piece the loop assemblage is running connected component $i, the IAP is already astatine component $i+1. This is the ground wherefore codification samples exhibiting modification throughout iteration volition ever unset the adjacent component, instead than the actual 1.

Examples: Your trial circumstances

The 3 features described supra ought to supply you with a largely absolute belief of the idiosyncrasies of the foreach implementation and we tin decision connected to discourse any examples.

The behaviour of your trial instances is elemental to explicate astatine this component:

  • Successful trial circumstances 1 and 2 $array begins disconnected with refcount=1, truthful it volition not beryllium duplicated by foreach: Lone the refcount is incremented. Once the loop assemblage subsequently modifies the array (which has refcount=2 astatine that component), the duplication volition happen astatine that component. Foreach volition proceed running connected an unmodified transcript of $array.
  • Successful trial lawsuit three, erstwhile once more the array is not duplicated, frankincense foreach volition beryllium modifying the IAP of the $array adaptable. Astatine the extremity of the iteration, the IAP is NULL (that means iteration has performed), which all signifies by returning mendacious.
  • Successful trial circumstances four and 5 some all and reset are by-mention features. The $array has a refcount=2 once it is handed to them, truthful it has to beryllium duplicated. Arsenic specified foreach volition beryllium running connected a abstracted array once more.

Examples: Results of actual successful foreach

A bully manner to entertainment the assorted duplication behaviors is to detect the behaviour of the actual() relation wrong a foreach loop. See this illustration:

foreach ($array arsenic $val) { var_dump(actual($array)); } /* Output: 2 2 2 2 2 */ 

Present you ought to cognize that actual() is a by-ref relation (really: like-ref), equal although it does not modify the array. It has to beryllium successful command to drama good with each the another features similar adjacent which are each by-ref. By-mention passing implies that the array has to beryllium separated and frankincense $array and the foreach-array volition beryllium antithetic. The ground you acquire 2 alternatively of 1 is besides talked about supra: foreach advances the array pointer earlier moving the person codification, not last. Truthful equal although the codification is astatine the archetypal component, foreach already precocious the pointer to the 2nd.

Present lets attempt a tiny modification:

$ref = &$array; foreach ($array arsenic $val) { var_dump(actual($array)); } /* Output: 2 three four 5 mendacious */ 

Present we person the is_ref=1 lawsuit, truthful the array is not copied (conscionable similar supra). However present that it is a mention, the array nary longer has to beryllium duplicated once passing to the by-ref actual() relation. Frankincense actual() and foreach activity connected the aforesaid array. You inactive seat the disconnected-by-1 behaviour although, owed to the manner foreach advances the pointer.

You acquire the aforesaid behaviour once doing by-ref iteration:

foreach ($array arsenic &$val) { var_dump(actual($array)); } /* Output: 2 three four 5 mendacious */ 

Present the crucial portion is that foreach volition brand $array an is_ref=1 once it is iterated by mention, truthful fundamentally you person the aforesaid occupation arsenic supra.

Different tiny saltation, this clip we’ll delegate the array to different adaptable:

$foo = $array; foreach ($array arsenic $val) { var_dump(actual($array)); } /* Output: 1 1 1 1 1 */ 

Present the refcount of the $array is 2 once the loop is began, truthful for erstwhile we really person to bash the duplication upfront. Frankincense $array and the array utilized by foreach volition beryllium wholly abstracted from the outset. That’s wherefore you acquire the assumption of the IAP wherever it was earlier the loop (successful this lawsuit it was astatine the archetypal assumption).

Examples: Modification throughout iteration

Attempting to relationship for modifications throughout iteration is wherever each our foreach troubles originated, truthful it serves to see any examples for this lawsuit.

See these nested loops complete the aforesaid array (wherever by-ref iteration is utilized to brand certain it truly is the aforesaid 1):

foreach ($array arsenic &$v1) { foreach ($array arsenic &$v2) { if ($v1 == 1 && $v2 == 1) { unset($array[1]); } echo "($v1, $v2)\n"; } } // Output: (1, 1) (1, three) (1, four) (1, 5) 

The anticipated portion present is that (1, 2) is lacking from the output due to the fact that component 1 was eliminated. What’s most likely surprising is that the outer loop stops last the archetypal component. Wherefore is that?

The ground down this is the nested-loop hack described supra: Earlier the loop assemblage runs, the actual IAP assumption and hash is backed ahead into a HashPointer. Last the loop assemblage it volition beryllium restored, however lone if the component inactive exists, other the actual IAP assumption (any it whitethorn beryllium) is utilized alternatively. Successful the illustration supra this is precisely the lawsuit: The actual component of the outer loop has been eliminated, truthful it volition usage the IAP, which has already been marked arsenic completed by the interior loop!

Different effect of the HashPointer backup+reconstruct mechanics is that modifications to the IAP done reset() and so forth. normally bash not contact foreach. For illustration, the pursuing codification executes arsenic if the reset() have been not immediate astatine each:

$array = [1, 2, three, four, 5]; foreach ($array arsenic &$worth) { var_dump($worth); reset($array); } // output: 1, 2, three, four, 5 

The ground is that, piece reset() briefly modifies the IAP, it volition beryllium restored to the actual foreach component last the loop assemblage. To unit reset() to brand an consequence connected the loop, you person to moreover distance the actual component, truthful that the backup/reconstruct mechanics fails:

$array = [1, 2, three, four, 5]; $ref =& $array; foreach ($array arsenic $worth) { var_dump($worth); unset($array[1]); reset($array); } // output: 1, 1, three, four, 5 

However, these examples are inactive sane. The existent amusive begins if you retrieve that the HashPointer reconstruct makes use of a pointer to the component and its hash to find whether or not it inactive exists. However: Hashes person collisions, and pointers tin beryllium reused! This means that, with a cautious prime of array keys, we tin brand foreach accept that an component that has been eliminated inactive exists, truthful it volition leap straight to it. An illustration:

$array = ['EzEz' => 1, 'EzFY' => 2, 'FYEz' => three]; $ref =& $array; foreach ($array arsenic $worth) { unset($array['EzFY']); $array['FYFY'] = four; reset($array); var_dump($worth); } // output: 1, four 

Present we ought to usually anticipate the output 1, 1, three, four in accordance to the former guidelines. However what occurs is that 'FYFY' has the aforesaid hash arsenic the eliminated component 'EzFY', and the allocator occurs to reuse the aforesaid representation determination to shop the component. Truthful foreach ends ahead straight leaping to the recently inserted component, frankincense abbreviated-slicing the loop.

Substituting the iterated entity throughout the loop

1 past unusual lawsuit that I’d similar to notation, it is that PHP permits you to substitute the iterated entity throughout the loop. Truthful you tin commencement iterating connected 1 array and past regenerate it with different array midway done. Oregon commencement iterating connected an array and past regenerate it with an entity:

$arr = [1, 2, three, four, 5]; $obj = (entity) [6, 7, eight, 9, 10]; $ref =& $arr; foreach ($ref arsenic $val) { echo "$val\n"; if ($val == three) { $ref = $obj; } } /* Output: 1 2 three 6 7 eight 9 10 */ 

Arsenic you tin seat successful this lawsuit PHP volition conscionable commencement iterating the another entity from the commencement erstwhile the substitution has occurred.

PHP 7

Hashtable iterators

If you inactive retrieve, the chief job with array iteration was however to grip removing of parts mid-iteration. PHP 5 utilized a azygous inner array pointer (IAP) for this intent, which was slightly suboptimal, arsenic 1 array pointer had to beryllium stretched to activity aggregate simultaneous foreach loops and action with reset() and many others. connected apical of that.

PHP 7 makes use of a antithetic attack, particularly, it helps creating an arbitrary magnitude of outer, harmless hashtable iterators. These iterators person to beryllium registered successful the array, from which component connected they person the aforesaid semantics arsenic the IAP: If an array component is eliminated, each hashtable iterators pointing to that component volition beryllium precocious to the adjacent component.

This means that foreach volition nary longer usage the IAP astatine each. The foreach loop volition beryllium perfectly nary consequence connected the outcomes of actual() and so forth. and its ain behaviour volition ne\’er beryllium influenced by capabilities similar reset() and many others.

Array duplication

Different crucial alteration betwixt PHP 5 and PHP 7 relates to array duplication. Present that the IAP is nary longer utilized, by-worth array iteration volition lone bash a refcount increment (alternatively of duplication the array) successful each circumstances. If the array is modified throughout the foreach loop, astatine that component a duplication volition happen (in accordance to transcript-connected-compose) and foreach volition support running connected the aged array.

Successful about circumstances, this alteration is clear and has nary another consequence than amended show. Nevertheless, location is 1 juncture wherever it outcomes successful antithetic behaviour, particularly the lawsuit wherever the array was a mention beforehand:

$array = [1, 2, three, four, 5]; $ref = &$array; foreach ($array arsenic $val) { var_dump($val); $array[2] = zero; } /* Aged output: 1, 2, zero, four, 5 */ /* Fresh output: 1, 2, three, four, 5 */ 

Antecedently by-worth iteration of mention-arrays was particular instances. Successful this lawsuit, nary duplication occurred, truthful each modifications of the array throughout iteration would beryllium mirrored by the loop. Successful PHP 7 this particular lawsuit is gone: A by-worth iteration of an array volition ever support running connected the first parts, disregarding immoderate modifications throughout the loop.

This, of class, does not use to by-mention iteration. If you iterate by-mention each modifications volition beryllium mirrored by the loop. Curiously, the aforesaid is actual for by-worth iteration of plain objects:

$obj = fresh stdClass; $obj->foo = 1; $obj->barroom = 2; foreach ($obj arsenic $val) { var_dump($val); $obj->barroom = forty two; } /* Aged and fresh output: 1, forty two */ 

This displays the by-grip semantics of objects (i.e. they behave mention-similar equal successful by-worth contexts).

Examples

Fto’s see a fewer examples, beginning with your trial instances:

  • Trial circumstances 1 and 2 hold the aforesaid output: By-worth array iteration ever support running connected the first components. (Successful this lawsuit, equal refcounting and duplication behaviour is precisely the aforesaid betwixt PHP 5 and PHP 7).
  • Trial lawsuit three adjustments: Foreach nary longer makes use of the IAP, truthful all() is not affected by the loop. It volition person the aforesaid output earlier and last.
  • Trial instances four and 5 act the aforesaid: all() and reset() volition duplicate the array earlier altering the IAP, piece foreach inactive makes use of the first array. (Not that the IAP alteration would person mattered, equal if the array was shared.)

The 2nd fit of examples was associated to the behaviour of actual() nether antithetic mention/refcounting configurations. This nary longer makes awareness, arsenic actual() is wholly unaffected by the loop, truthful its instrument worth ever stays the aforesaid.

Nevertheless, we acquire any absorbing adjustments once contemplating modifications throughout iteration. I anticipation you volition discovery the fresh behaviour saner. The archetypal illustration:

$array = [1, 2, three, four, 5]; foreach ($array arsenic &$v1) { foreach ($array arsenic &$v2) { if ($v1 == 1 && $v2 == 1) { unset($array[1]); } echo "($v1, $v2)\n"; } } // Aged output: (1, 1) (1, three) (1, four) (1, 5) // Fresh output: (1, 1) (1, three) (1, four) (1, 5) // (three, 1) (three, three) (three, four) (three, 5) // (four, 1) (four, three) (four, four) (four, 5) // (5, 1) (5, three) (5, four) (5, 5) 

Arsenic you tin seat, the outer loop nary longer aborts last the archetypal iteration. The ground is that some loops present person wholly abstracted hashtable iterators, and location is nary longer immoderate transverse-contamination of some loops done a shared IAP.

Different bizarre border lawsuit that is fastened present, is the unusual consequence you acquire once you distance and adhd components that hap to person the aforesaid hash:

$array = ['EzEz' => 1, 'EzFY' => 2, 'FYEz' => three]; foreach ($array arsenic &$worth) { unset($array['EzFY']); $array['FYFY'] = four; var_dump($worth); } // Aged output: 1, four // Fresh output: 1, three, four 

Antecedently the HashPointer reconstruct mechanics jumped correct to the fresh component due to the fact that it “regarded” similar it’s the aforesaid arsenic the eliminated component (owed to colliding hash and pointer). Arsenic we nary longer trust connected the component hash for thing, this is nary longer an content.