PHP loop through arrayObject

Home / Uncategorized / PHP loop through arrayObject

Question:
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?


Answer:
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
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *