Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I alter array keys and values while using a RecursiveArrayIterator?
    primarykey
    data
    text
    <p>I suspect I'm doing something stupid here, but I'm confused by what seems like a simple problem with SPL:</p> <p>How do I modified the contents of an array (the values in this example), using a <a href="http://php.net/RecursiveArrayIterator" rel="noreferrer">RecursiveArrayIterator</a> / <a href="http://php.net/RecursiveIteratorIterator" rel="noreferrer">RecursiveIteratorIterator</a>?</p> <p>Using the follow test code, I can alter the value within the loop using <a href="http://php.net/iteratoriterator.getinneriterator" rel="noreferrer">getInnerIterator()</a> and <a href="http://php.net/ArrayAccess.offsetSet" rel="noreferrer">offsetSet()</a>, and dump out the modified array while I'm within the loop.</p> <p>But when I leave the loop and dump the array from the iterator, it's back to the original values. What's happening?</p> <pre><code>$aNestedArray = array(); $aNestedArray[101] = range(100, 1000, 100); $aNestedArray[201] = range(300, 25, -25); $aNestedArray[301] = range(500, 0, -50); $cArray = new ArrayObject($aNestedArray); $cRecursiveIter = new RecursiveIteratorIterator(new RecursiveArrayIterator($cArray), RecursiveIteratorIterator::LEAVES_ONLY); // Zero any array elements under 200 while ($cRecursiveIter-&gt;valid()) { if ($cRecursiveIter-&gt;current() &lt; 200) { $cInnerIter = $cRecursiveIter-&gt;getInnerIterator(); // $cInnerIter is a RecursiveArrayIterator $cInnerIter-&gt;offsetSet($cInnerIter-&gt;key(), 0); } // This returns the modified array as expected, with elements progressively being zeroed print_r($cRecursiveIter-&gt;getArrayCopy()); $cRecursiveIter-&gt;next(); } $aNestedArray = $cRecursiveIter-&gt;getArrayCopy(); // But this returns the original array. Eh?? print_r($aNestedArray); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload