how iterate ArrayCollection in symfony2 Controller
Definitely agree one shouldn't convert to an array, however, ->getIterator()
isn't necessary.
foreach($arrayCollection as $i => $item) {
//do things with $item
}
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
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
}