Thus if you change the reference the original value will change. While pass by reference in foreach or functions is a clean and short solution, for many beginners this might be a dangerous pitfall.
Lots of people think the answer is two because it uses "reference to value, which it doesn't have to copy each value when it loops".
Well, that's totally wrong! The array itself wasn't passed by reference to the function, so PHP knows that it isn't allowed to modify the outside array, so it therefore makes a copy of the array's internal iteration offset state that's just a simple number which says which item you are currently at during things like foreachwhich costs almost no performance or memory at all since it's just a small number.
That's what MANY people think.
But the answer is NO. It re-uses the existing value in memory. With zero performance cost. Alright, so what's the second version doing? The beloved "iterate values by reference"? The array itself wasn't passed by reference to the function, so PHP knows that it isn't allowed to modify the outside array.
If we just give them references to the original array's values, and they assign some new value to their reference, they would destroy the original array which they aren't allowed to touch! It's almost always BAD! With worse performance, and risks of bugs and quirks as is demonstrated in the manual.
You can always manually write array assignments explicitly, without references, like this:I'm certain this is VERY simple, but being new and not knowing what I'm doing I can't quite get it on my own.
I am trying to create an array of wordpress post ID's that is derived from a simple foreach loop. The PHP foreach Loop. The foreach loop works only on arrays, and is used to loop through each key/value pair in an array..
Syntax. In PHP 5, when foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop. As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.
The issue gets even more complicated when the array itself is a reference. Foreach performance. In general PHP prefers pass by value due to the copy-on-write feature.
It means that internally PHP will not create a duplicate data unless the copy of it needs to be changed. Now that the IAP is no longer used, by-value array iteration will only do a refcount increment (instead of duplication the array) in all cases.
If the array is modified during the foreach loop, at that point a duplication will occur (according to copy-on-write) and foreach will keep working on the old array. These versions do not perform copy-on-write when the function result is used directly inside the foreach block.
As such, the original array is now used and changes to the elements are permanent. I personally feel that this is a bug; copy-on-write should have taken place. PHP >