Search code examples
phploopsarrayobject

PHP loop through ArrayObject


This is the first time I work with ArrayObjects so maybe I didn't understand it 100% but could you please explain me how to loop through them?

This is my code:

$this->plugins = new \ArrayObject(array());
//just for testing...
$this->plugins->plugin1 = "plugin1";
$this->plugins->plugin2 = "plugin2";
$this->plugins->plugin3 = "plugin3";

foreach ($this->plugins as $plugin){
     //never reached
}

$this->plugins->count() returns 0 and $this->plugins->getIterator()->valid(); returns false as well. What do I have to do?


Solution

  • You have gotten far but this is how it works

    // You can already have an array like this
    $array = array('Buck','Jerry','Tomas');
    
    $arrayObject = new ArrayObject($array);
    // Add new element
    $arrayObject->append('Tweety');
    
    // We are getting the iterator of the object
    $iterator = $arrayObject->getIterator();
    
    // Simple while loop
    while ($iterator->valid()) {
        echo $iterator->current() . "\n";
        $iterator->next();
    }
    

    Source