![]() Results in an infinite loop, even though $item isn’t by reference. We know that referencing $item will cause the infinite loop scenario above, but if $set is referenced anywhere else in the script, even the non-referencing foreach format will break: PHP fails to create a copy of the array if a reference is used at all. When a copy is created and used only by the structure of the loop construct itself, the array stays static throughout the execution of the loop, so you’ll never run into issues.īut wait, there’s more. ![]() So in this previous example with the infinite loop, we see the reason why PHP was written to create a copy of the array to loop over. I added the following line to my script so PHP would run out of memory very quickly, I suggest you do the same if you’re going to be running these infinite loop tests: Note this actually is an infinite loop, you’ll have to either kill the script yourself or wait for your OS to run out of memory. $set = array( "apple", "banana", "coconut" ) However, what if we had used $item by reference, as I mentioned before? A single character added to the above test: Because of this, the loop above only executes 3 times, and each time it appends another value to the end of the original $set, leaving the original $set with 6 elements, but never entering an infinite loop. Basically, PHP is only using the copied array for the execution of the loop and the assignment of $item. In this example, PHP copied $set and used it to loop over, but when $set was used inside the loop, PHP added the variables to the original array, not the copied array.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |