views:

74

answers:

3

Saw this in wikipedia, this is what happens when you traverse an iterator via a foreach loop:

These methods are all being used in a complete foreach( $object as $key=>$value ) sequence. The methods are executed in the following order:

rewind() 
while valid() {
    current() in $value 
    key() in $key 
    next()
} 
End of Loop

I was wondering how I can access the values of next() and rewind(). Any ideas?

UPDATE: Access them from inside the foreach loop

A: 

IF its implementing the Iterator interface you can call those method yourself but they have implications.

rewind and next both set the position of the pointer in the dataset being iterated over... they dont actually return the element or index. So calling either of these is going to screw up your loop.

current will return the same variable you already have in the loop - ie. the element for the current iteration. key will return the index for that item in the set.

prodigitalson
+2  A: 

What do you think about it?

for ($i =0; $i < count($arr); $i++) {

    $last = ($i == 0) ? null : $arr[$i-1];
    $next = (isset($arr[$i+1]) ? $arr[$i+1] : null;
    $current = $arr[$i];

    //...

}
Felipe Cardoso Martins
Won't work in general (the keys may not be integers, or they may not start with 0 and be sequential).
Artefacto
A: 

You can't. To trigger a reset, you'd need to reenter the loop, and to call next, you need to go into the next iteration.

So the closest (PHP 5.3) would be this:

label:
foreach ($var as $k => $v) {

    /* ... */
    goto label; //re-enter loop

    /* ... */
    continue; //force going to the next iteration

    /* ... */
}

If you are using iterators directly, you can use those calls:

$r = 0; $s = 0;
$it = new ArrayIterator(array("a" => 3, "b" => 5, "c" => 7));
foreach ($it as $k => $v) {
    echo "$k => $v\n";
    if ($s == 0) {
        $s = 1;
        $it->next(); //jump over one iteration
    } else if ($r == 0) {
        $r = 1;
        $it->rewind();
    }
}

gives:

a => 3
c => 7
b => 5
c => 7
Artefacto