php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #79203 Inconsistent behaviour of ArrayIterator
Submitted: 2020-01-31 13:59 UTC Modified: -
From: mail at dabla dot ch Assigned:
Status: Open Package: SPL related
PHP Version: 7.4.2 OS: Linux
Private report: No CVE-ID: None
 [2020-01-31 13:59 UTC] mail at dabla dot ch
Description:
------------
When calling offsetUnset for the only element in an ArrayObject and then append one item, the resulting position of an associated ArrayIterator doesn't seem to be well defined.

Steps to reproduce:
- Create an ArrayObject with one item.
- Get an ArrayIterator for the ArrayObject.
- Repeat:
  - Call offsetUnset with the key of the one element in the array.
    Note: Calling offsetUnset on the array or the iterator does not change the 
    behaviour.
  - Append an item to the ArrayObject.
  - check if the iterator is valid

Until php 7.2 the iterator did always point to the appended element.

Test script:
---------------
<?php
$a = new ArrayObject(['item']);
$i = $a->getIterator();

for($c = 0; $c < 100; $c++) {
	echo ($i->valid() ? 'valid' : 'invalid') . PHP_EOL;
	if($i->valid()) {
		$a->offsetUnset($i->key());
	}
	$a->append('item');
}



Expected result:
----------------
The behaviour should at least be consistent. It would be best to have the same behaviour as with php7.2, meaning the test script would always output "valid".

Actual result:
--------------
The behaviour is inconsistent. The test script outputs:
valid
valid
valid
valid
valid
valid
valid
valid
invalid
invalid
invalid
invalid
invalid
invalid
invalid
invalid
valid
invalid
valid
invalid

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-01-31 14:29 UTC] mail at dabla dot ch
The test script does not do exactly the described thing. This would be more accurate:

$a = new ArrayObject(['item']);
$i = $a->getIterator();

for($c = 0; $c < 20; $c++) {
	echo ($i->valid() ? 'valid' : 'invalid') . PHP_EOL;
	if(!$i->valid()) {
		$i->rewind();
	}
	$a->offsetUnset($i->key());
	$a->append('item');
}
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Dec 30 14:01:28 2024 UTC