Doctrine: Sorting a Collection by Array

Let’s assume you have a Doctrine Collection which you want to sort by a custom array of IDs.

To sort a Doctrine Collection you have to use an ArrayCollection:

use Doctrine\Common\Collections\ArrayCollection;$result = $this->getEntityManager()
->from('MyEntity', 'e')

$myArrayCollection = new ArrayCollection($result);

The Doctrine ArrayCollection has different methods for accessing the collection as an array. We will use the getIterator() method to create an ArrayIterator and the uasort() method to create a custom comparison function:

// 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;

$myArrayCollectionIterator is now sorted by the values of $myCustomIdArray.

Web Developer in Berlin —

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store