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
}
                        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
                        Definitely agree one shouldn't convert to an array, however, ->getIterator() isn't necessary.
foreach($arrayCollection as $i => $item) {
    //do things with $item
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With