Robin Schambach
Robin Schambach

Reputation: 846

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?

Upvotes: 1

Views: 1724

Answers (2)

von Oak
von Oak

Reputation: 833

Your code is almost ok, only change initialization of variables, so instead plugins->plugin1 = "plugin1", put everything into array("plugin1", ...) on the beginning. So

$plugins = new ArrayObject(array("plugin1", "plugin2", "plugin3"));

foreach ($plugins as $plugin){
    echo $plugin . "<br>";
}

Upvotes: 0

Anna Jeanine
Anna Jeanine

Reputation: 4125

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

Upvotes: 4

Related Questions