Doctrine: Sorting a Collection by Array

KC Müller
Jul 19 · 1 min read
use Doctrine\Common\Collections\ArrayCollection;$result = $this->getEntityManager()
->from('MyEntity', 'e')

$myArrayCollection = new ArrayCollection($result);
// custom array for sorting by id
$myCustomIdArray = [1331,1212,119];
$myArrayCollectionIterator = $myArrayCollection->getIterator();

function ($first, $second) use ($myCustomIdArray) {
foreach ($myCustomIdArray as $myCustomId) {
if ($first->getCustomId() === $myCustomId) {
return -1;
if ($second->getCustomId() === $myCustomId) {
return 1;
// if value is not found in $myCustomIdArray
return 0;

KC Müller

Written by

Web Developer in Berlin —

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade