Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: foreach an array objects, how to move internal pointer to the next one?

Tags:

php

I need to loop and array of objects. In some cases, inside the loop, I need to move the internal pointer to the next element in the array. How do I do that?

foreach($objects as $object)
{
   // TODO: move internal pointer to next one?
   // next($objects) doesn't work
}
like image 703
StackOverflowNewbie Avatar asked Dec 09 '22 11:12

StackOverflowNewbie


1 Answers

You can't move the array pointer, but you can skip the iteration:

foreach ($objects as $object) {
    if (!interesting($object)) {
        continue;
    }

    // business as usual
}

If you need to decide whether to skip the next iteration, you can do something like this:

$skip = false;

foreach ($objects as $object) {
    if ($skip) {
        $skip = false;
        continue;
    }

    // business as usual

    if (/* something or other */) {
        $skip = true;
    }
}

I'd first check if there isn't any better logic to express what you want though. If there isn't, @netcoder's list each example is the more concise way of doing this.

like image 61
deceze Avatar answered May 22 '23 08:05

deceze