4

its good that there is iterator to array http://php.net/manual/en/function.iterator-to-array.php but is there anything to do it reversed?

John Smith
  • 6,129
  • 12
  • 68
  • 123

2 Answers2

8

Yes, if reversed means just make an Iterator from a given Array.

$array = array(
  'a' => 1,
  2 => new stdClass,
  3 => array('subArrayStuff'=>'value')
);

$iterator = new ArrayObject($array);

$arrayAgain = iterator_to_array($iterator);

Try it.

http://php.net/manual/en/class.arrayobject.php

Please read also Difference between ArrayIterator, ArrayObject and Array in PHP.

apaderno
  • 28,547
  • 16
  • 75
  • 90
JustOnUnderMillions
  • 3,741
  • 9
  • 12
0

http://php.net/manual/en/class.iterator.php Here's an example of MyIterator that uses an array. You can change the constructor and pass there any array

class myIterator implements Iterator {
    private $position = 0;
    private $array = array();  

    public function __construct($data = array()) {
        $this->array = $data;
        $this->position = 0;
    }

    function rewind() {
        var_dump(__METHOD__);
        $this->position = 0;
    }

    function current() {
        var_dump(__METHOD__);
        return $this->array[$this->position];
    }

    function key() {
        var_dump(__METHOD__);
        return $this->position;
    }

    function next() {
        var_dump(__METHOD__);
        ++$this->position;
    }

    function valid() {
        var_dump(__METHOD__);
        return isset($this->array[$this->position]);
    }
}
Richard
  • 1,045
  • 7
  • 11
  • 1
    A little cheeky copying the manual page, when a comment with a link would have achieved the same thing – RiggsFolly May 27 '16 at 14:31
  • 2
    I've made the changes. Otherwise I would left the link in the comment. But yeah, it's based on copying from manual – Richard May 27 '16 at 14:32