Copying of arrays

php.internals

Ilia A.

23 years ago
Bug #23195 demonstrates an interesting in the way arrays are copied in PHP. If inside the code that depends on the position of the array the array is copied to another variable it's internal position gets reset. This, as the example below will show will cause an unterminated loop. <?php $arr = array('a', 'b'); while (each($arr)) $arr2 = $arr; ?> The source of the problem could be traced to zend_hash_copy(), which will always reset the internal pointer of the target array to the 'head' element. This can be remedied by setting the internal pointer of the new array to the same as the source array, which solves the problem (patch attached). Or we document this problem and tell people to assign values by reference if they need to assign an array, which is being traversed to another variable. Ilia