I have a problem with ArrayIterator::valid()
method. It always return true. I don't know if I don't understand how should it work, or am I doing something wrong...
I use Doctrine's Paginator
http://www.doctrine-project.org/api/orm/2.1/source-class-Doctrine.ORM.Tools.Pagination.Paginator.html
It does implement \Countable
and \IteratorAggregate
. The method getIterator()
returns \ArrayIterator
.
In view I do:
<?php foreach ($this->paginator as $message): ?>
<?php var_dump($this->paginator->valid()); ?> // Fatal error. Method does not exist
<?php var_dump($this->paginator->getIterator()->valid()); ?> // <-- it always return true
<p>Teeeeeest</p>
<?php endforeach; ?>
I also tried:
<?php $paginator = $this->paginator->getIterator(); ?>
<?php foreach ($paginator as $message): ?>
<?php var_dump($paginator->valid()); ?> // <-- it always return true
<p>Teeeeeest</p>
<?php endforeach; ?>
var_dump($this->paginator)
shows that I have 2 records. So I should get true
in first iteration and false
in second iteration. Am I correct? So why does it return always true
The foreach takes only valid entries, so $paginator->valid()
is always valid at this point. If you use $paginator->next()
that will end in false
after the last entry was proccessed.
So $paginator->valid()
is used with $paginator->next()
not within a foreach
Try to test it like that.
$paginator->reset();
while($paginator->valid()){
$entrie = $paginator->current();
$paginator->next();
}
or test it with var_dump($paginator->valid());
after the foreach. (But maybe the foreach will reset the iterator after iteration)
:-)