[php-src] Issue #25107: array_unshift() skips unvisited values in foreach by reference when the array has holes

From: Date: Sat, 31 Oct 2026 18:37:57 +0000
Subject: [php-src] Issue #25107: array_unshift() skips unvisited values in foreach by reference when the array has holes
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-253960@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/25107 Author: JoaoMarcos44 ### Description > AI-assisted report. The explanation was prepared with AI assistance. The reproduction and > outputs below were verified by local execution. > Calling array_unshift() during a > foreach by reference can skip an unvisited element when deleted > entries leave holes before the iterator position. This can silently omit work items. ```php <?php $items = ['a', 'b', 'c', 'd']; unset($items[0]); $seen = []; foreach ($items as &$item) { $seen[] = $item; if ($item === 'b') { array_unshift($items, 'x'); } } unset($item); echo json_encode($seen), "\n"; ``` > Actual output: ```text ["b","d"] ``` > Expected output: ```text ["b","c","d"] ``` > The [PHP 7 foreach RFC](https://wiki.php.net/rfc/php7_foreach) and > Zend/tests/foreach/foreach_016.phpt specify that > array_unshift() preserves reference-iterator positions. This case > also reproduces with string-keyed arrays. The rebuild compacts deleted slots, but the iterator > adjustment only adds the number of prepended values to the old position. > Related PR #24475 optimizes the path without holes or active iterators; its current fallback > retains the affected iterator adjustment. ### PHP Version ```text PHP 8.5.12 (cli) (built: Oct 28 2026 01:23:38) (NTS) Copyright (c) The PHP Group Built by https://github.com/docker-library/php Zend Engine v4.5.12, Copyright (c) Zend Technologies with Zend OPcache v8.5.12, Copyright (c), by Zend Technologies ``` > Also reproduced on PHP 8.7.0-dev at commit > 248c5c45409667b5e69bba38a92c5cc9edd7582a. ### Operating System Debian GNU/Linux 12 (bookworm), Linux container.

« previous php.bugs (#253960) next »