skip to Main Content
$list = new ArrayIterator(array('page1', 'page2', 'page3', 'page4'));
echo $list->current(); // 'page1'
$list->next();
echo $list->current(); // 'page2'

// What I want to achieve
$list->previous();
echo $list->current(); // 'page1'

From there, how can I get last element page1 ?

2

Answers


  1. Chosen as BEST ANSWER

    You can use seek() method and key index to move internal pointer to last element

    $list->seek($list->key() - 1);
    

    Full example

    $list = new ArrayIterator(array('page1', 'page2', 'page3', 'page4'));
    echo $list->current(); // 'page1'
    $list->next();
    echo $list->current(); // 'page2'
    
    $list->seek($list->key() - 1);
    echo $list->current(); // 'page1'
    

  2. I had this problem with an associative ArrayIterator, and this works both for simple and associative arrays, if you track the numeric position of the pointer as you cycle through the array …

    $list = new ArrayIterator(
        [
            'foo'  => 'page1',
            'bar'  => 'page2',
            'baz'  => 'page3',
            'qux'  => 'page4',
            'fred' => 'page5'
        ]
    );
    $numericIndex = -1;
    foreach ($list as $key => $value) {
        $numericIndex++;
        var_dump($list->current());
        if ($key === 'bar') {
            // Jump ahead to do stuff to the following elements
            $list->next();
            var_dump('Jumped ahead to: ' . $list->current());
            $list->next();
            var_dump('Jumped ahead to: ' . $list->current());
    
            // Rewind to original position to continue the loop 
            $list->seek($numericIndex);
        }
    }
    

    That outputs:

    ...:string 'page1' (length=5)
    ...:string 'page2' (length=5)
    ...:string 'Jumped ahead to: page3' (length=22)
    ...:string 'Jumped ahead to: page4' (length=22)
    ...:string 'page3' (length=5)
    ...:string 'page4' (length=5)
    ...:string 'page5' (length=5)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search