开发者

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

开发者 https://www.devze.com 2023-02-07 03:06 出处:网络
I need to loop and array of objects. In some cases, 开发者_如何学Pythoninside the loop, I need to move the internal pointer to the next element in the array. How do I do that?

I need to loop and array of objects. In some cases, 开发者_如何学Pythoninside 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
}


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.


As previously mentioned, you can use a for loop (only if you have numeric keys though) or continue. Another alternative is to use the list and each iteration method which allows you to move the array pointer with next, prev, etc. (as it does not create a copy of the array like foreach does):

$array = array(1,2,3,4,5);

while (list($key, $value) = each($array)) {
   echo $value;
   next($array);
}

Will output:

024


Now, that I understand, what you want ;), two other solutions

$c = count($array);
for ($i = 0; $i < $c; $i += 2) {
  $item = $array[$i];
}

foreach (range(0, count($array), 2) as $i) {
  $item = $array[$i];
}


next($objects)

next — Advance the internal array pointer of an array


Use for loop, like this:

for($i = 0; $i < sizeof($array); $i++)
{
    echo $array[$i]->objectParameter;
    $i++; //move internal pointer
    echo $array[$i]->objectParameter;
    $i++; //move internal pointer again
    echo $array[$i]->objectParameter;
    //$i++; //no need for this because for loop does that
}
0

精彩评论

暂无评论...
验证码 换一张
取 消