Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return items from array sequentially on each function call, false when no more exist

Tags:

php

I need to have a function that sort of acts like mysql resources sometimes do, where you have to "fetch" something as part of a loop until it returns false.

I have something like:

while ($variable = $object->method())
{
  // Do stuff with variable here
}

I'm trying to figure out how, on my object, to best keep track of what to send from the method.

class object {
  $values = array(1, 2);
  public function method()
    {
      // First call should return 1, second should return 2, and any subsequent calls should return FALSE
      // Not sure now what to do
      // return $values[$i];
    }
}
like image 767
Matthew Avatar asked Apr 17 '26 00:04

Matthew


1 Answers

Use the each() function. It moves the array's internal pointer and returns the current value. If no more values are present, it returns false.

return each($values);

it also has the advantage of not being destructive.

like image 151
Maerlyn Avatar answered Apr 18 '26 14:04

Maerlyn