Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using count() on a class that implements Iterator in PHP

Quick question really:

I've seen in bits of code in the past where the code could call count() on a object that implements Iterator, for custom Iterator classes.

I've written a class that implements Iterator and works fine in a foreach loop, but I was just wondering if there was an extra class I had to extend or function I had to implement in order for count() to work on my class, to return a value I want.

like image 474
wiggles Avatar asked Sep 15 '10 20:09

wiggles


2 Answers

I don't have much experience with Iterators, but this looks like what you're looking for:

The Countable interface

Classes implementing Countable can be used with the count() function.

like image 189
Pekka Avatar answered Nov 17 '22 17:11

Pekka


If you only have to do a count on your Iterator class, you can use the iterator_count() function.

like image 42
COil Avatar answered Nov 17 '22 16:11

COil