Skip to content

Instantly share code, notes, and snippets.

@enygma
Created October 22, 2016 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enygma/c3fff1ceb3f6b6643ae5c7b182a81f53 to your computer and use it in GitHub Desktop.
Save enygma/c3fff1ceb3f6b6643ae5c7b182a81f53 to your computer and use it in GitHub Desktop.
Is this a bug with the iterator handling and foreach?
<?php
/**
* In the example below, I make an iterator and assign three values to it: "foo", "bar" and "baz".
* I then manually remove the first one (index 0) and pass the rest into foreach. I expected it
* to just start with index 1 and go on and loop through the rest but there's no output at all.
*
* Is this a bug?
*/
class Items implements \Iterator
{
private $items = [];
private $index = 0;
public function current()
{
return $this->items[$this->index];
}
public function next()
{
$this->index++;
}
public function valid()
{
return isset($this->items[$this->index]);
}
public function key()
{
return $this->index;
}
public function rewind()
{
$this->index = 0;
}
public function add($item)
{
$this->items[] = $item;
}
public function remove($index)
{
unset($this->items[$index]);
}
}
//-------------------
$items = new Items();
$items->add('foo');
$items->add('bar');
$items->add('baz');
$items->remove(0);
// Expected that the loop would start with the first index of "1"
// but it doesn't output anything
foreach($items as $item) {
echo $item."\n";
}
@andytson
Copy link

@enygma how about changing the unset($this->items[$index]); to array_splice($this->items, $index, 1);? This will reset the indices.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment