2

There are certain functions that we use from MongoDB driver like to iterate a cursor we can use "hasNext()" and "getNext()". But we can also use simple PHP's foreach to iterate cursor and we don't have to call the above methods.

My question is if foreach is simple PHP function, how does it work with MongoDB ? How does it fetches the records from cursor ? Does it internally use "cursor.forEach()" of MongoDB or does it internally runs "hasNext()" and "getNext()" ?

Any help would be greatly appreciated.

Dharmendra Yadav
  • 152
  • 1
  • 13

1 Answers1

3

The MongoCursor class implements Iterator interface. So, foreaching the cursor, is the same thing as calling $cursor->next(), then checking $cursor->valid() and then getting value from $cursor->current() (repeat until the valid is false). For $key => $value format it also gets value of $cursor->key().

It does some internal runs but it is not running "hasNext()", "getNext()", etc. It runs standard methods abstractly described in Iterator interface.

Sorry for my captiousness, but the foreach is not "simple PHP function"; it's a language construct. I've just found a good explanations about the difference here on Stack Overflow.

Community
  • 1
  • 1
Ronin
  • 1,688
  • 1
  • 13
  • 23