Sorting objects by their property in PHP

Sorting objects by their property in PHP

Created:10 Dec 2016 13:10:14 , in  Web development

Lets say you have got an array of assorted objects, each with the same set of properties, which are either numbers or strings, and you would like to sort them by one of those properties using PHP.

Since it is a fairly common requirement, you can expect the basic tools are already available to you. By basic tools I mean usort and strcmp PHP functions here.

Lets prepare some objects with a random number ('num') and a random string ( of length 1 ) ('str') as their property values:

$to_be_sorted = array();
$chars = 'abcdefg';
for($i = 0;$i< 3;$i++ ){
  $random_number = rand(1,99);
  $to_be_sorted[] = (object) [
    'num' => $random_number,
    'str' => $chars[$random_number % 7]

Sort by number

Now, to sort these objects by "num" which is a random number between 1 and 99 inclusive, the following can be done:

  return $a -> num > $b -> num;

To sort array $to_bo_sorted we used usort PHP function. It accepts an array ($to_be_sorted) as its first argument and a comparison functions as its second arguemnt. The anonymous function returns a number on the basis of which objects in the array will be sorted.

Sort by string

The same idea can be used to sort the same array of objects by "str" property which holds a string (of length 1, length of the string plays no role in this case). What differs here is, we use strcmp function which helps to return a numeric value from the comparison function.

  return (int)strcmp($a -> str,$b -> str);

The technique described above can be extended to properties of any type, like arrays for example. It will work as long as you can compare the property in some meaningful manner. More over it can be easily transferred to other programming languages like JavaScript, Python etc.

This post was updated on 25 May 2017 16:09:02

Tags:  php ,  sort 

Author, Copyright and citation


Sylwester Wojnowski

Author of the above article, Sylwester Wojnowski, enjoys sWWW writing computer code in PHP, JavaScript and BASH, and some other things he wrote more on on the About page of this website.


©Copyright, 2021 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.

Computer code, if present in the article, is excluded from the above and licensed under GPLv3.


Cite this article as:

Wojnowski, Sylwester. "Sorting objects by their property in PHP." From sWWW - Code For The Web .

Add Comment

Allowed BB Code - style tags: [b][/b], [i][/i], [code=text][/code],[code=javascript][/code],[code=php][/code],[code=bash][/code],[code=css][/code],[code=html][/code]

I constent to processing my data given through this form for purposes of a reply by the administrator of this website.

Recent Comments

Nobody has commented on this post yet. Be first!