Modification of array iterated through foreach by reference may cause undefined iteration behavior
Nobody has claimed this yet.
- Dominant language
- XML
- Stars
- 596
- Forks
- 890
- Avg merge
- 1d 15h
- Merged PRs (30d)
- 55
Description
Description
The following code:
<?php
function demo($array) {
$debug_backtrace = [];
foreach ($array as $key => &$value) {
echo "{$value}\r\n";
if ($value == 3) {
unset($array[$key]);
continue;
}
$debug_backtrace[] = debug_backtrace();
}
}
demo([1, 2, 3]);
Resulted in this output:
1
2
3
1
2
But I expected this output instead:
1
2
3
Please pay attention to usage of the ampersand for the $value.
Please note that commenting out the "$debug_backtrace[] = debug_backtrace();" will resolve the issue.
This happens for PHP 8.0.15 as well.
PHP Version
PHP 8.1.2
Operating System
Windows 11 & Ubuntu 20.04
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the supplied PHP snippet on PHP 8.1.2, then review the PHP documentation covering foreach by reference, unset, and debug_backtrace. Done means the relevant documentation clearly explains the observed iteration behavior and expected result.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- php
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100