1

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?

2
  • what if you create a simple array using $this->plugins->plugin1 .... Commented Aug 15, 2017 at 7:04
  • This would be a way to solve it too, but I would like to know how it works with ArrayObjects to understand and learn it. Commented Aug 15, 2017 at 7:15

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

So I have to use the append method in order to make it work? Thank you
@Anubarak Yes! If this solved your problem please accept the answer so it can help others too.
Thats what I'm going to do in 4 minutes - I have to wait a little bit :D
@Anubak You use append only when you want to add something to object. If you want to iterate through an object, you don't need use append at all.
0

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>";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.