20

I want to iterate ArrayCollection instance in Symfony2 Controller, What is the easiest way?

edit:

I thought it would work like normal array in php but I got error on this code:

foreach ($arrayCollectionInc as $Inc) {

}
5
  • You forgot to include what you've tried Commented Sep 4, 2014 at 14:26
  • 2
    foreach($collection as $item){ ... } Commented Sep 4, 2014 at 14:28
  • 2
    What was an error? ArrayCollection extends Collection which in turn implements IteratorAggregate and ArrayAccess ---> foreach should be possible... Commented Sep 4, 2014 at 15:18
  • and what error would that be ? Commented Sep 4, 2014 at 16:30
  • Hmmm.. I always got some error that say something like array needed but i insert ArrayCollection.. but now it work fine for me!!!!! Commented Sep 4, 2014 at 19:21

3 Answers 3

48

To those who find this question in the future there is another way that I would consider to be a better practice than the accepted answer, which just converts the ArrayCollection to an array. If you are going to just convert to an array why bother with the ArrayCollection in the first place?

You can easily loop over an ArrayCollection without converting it to an array by using the getIterator() function.

foreach($arrayCollection->getIterator() as $i => $item) {
    //do things with $item
}
Sign up to request clarification or add additional context in comments.

3 Comments

This should be considered best practice.
Why exactly? ArrayCollection implements IteratorAggregate. You should just foreach the array collection
One difference I found is that if you don't use getIterator() and you do $arrayCollection->key() inside the loop, you always get 0. But of course you can just do as $i => $item and you'll have your key without the need to call key().
14

Simplest way:

$arr = $arrayCollectionInc->toArray();

foreach ($arr as $Inc) {

}

Working example:

$a = new ArrayCollection();
$a->add("value1");
$a->add("value2");

$arr = $a->toArray();

foreach ($arr as $a => $value) {
    echo $a . " : " . $value . "<br />";
}

Result:

0 : value1
1 : value2

Comments

8

Definitely agree one shouldn't convert to an array, however, ->getIterator() isn't necessary.

foreach($arrayCollection as $i => $item) {
    //do things with $item
}

1 Comment

Have managed doing something like foreach($arrayCollection as $item) {// do something with $item} and it works just fine. Is there a performance difference that I'm missing, or an error I haven't encountered so far?

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.