Sort array of objects by object fields Sort array of objects by object fields php php

Sort array of objects by object fields


Use usort, here's an example adapted from the manual:

function cmp($a, $b) {    return strcmp($a->name, $b->name);}usort($your_data, "cmp");

You can also use any callable as the second argument. Here are some examples:

  • Using anonymous functions (from PHP 5.3)

      usort($your_data, function($a, $b) {return strcmp($a->name, $b->name);});
  • From inside a class

      usort($your_data, array($this, "cmp")); // "cmp" should be a method in the class
  • Using arrow functions (from PHP 7.4)

      usort($your_data, fn($a, $b) => strcmp($a->name, $b->name));

Also, if you're comparing numeric values, fn($a, $b) => $a->count - $b->count as the "compare" function should do the trick, or, if you want yet another way of doing the same thing, starting from PHP 7 you can use the Spaceship operator, like this: fn($a, $b) => $a->count <=> $b->count.


Heres a nicer way using closures

usort($your_data, function($a, $b){    return strcmp($a->name, $b->name);});

Please note this is not in PHP's documentation but if you using 5.3+ closures are supported where callable arguments can be provided.


If you want to sort integer values:

// Desc sortusort($array,function($first,$second){    return $first->number < $second->number;});// Asc sortusort($array,function($first,$second){    return $first->number > $second->number;});

UPDATEDwith the string don't forget to convert to the same register (upper or lower)

// Desc sortusort($array,function($first,$second){    return strtolower($first->text) < strtolower($second->text);});// Asc sortusort($array,function($first,$second){    return strtolower($first->text) > strtolower($second->text);});