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) {
}
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
}
$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().Definitely agree one shouldn't convert to an array, however, ->getIterator() isn't necessary.
foreach($arrayCollection as $i => $item) {
//do things with $item
}
foreach($collection as $item){ ... }ArrayCollectionextendsCollectionwhich in turn implementsIteratorAggregateandArrayAccess--->foreachshould be possible...