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:


usort($to_be_sorted,function($a,$b){
  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.


usort($to_be_sorted,function($a,$b){
  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

Author

Sylwester Wojnowski

Author of the above article, Sylwester Wojnowski, is sWWW admin and owner.He enjoys doing Maths and studying algorithms, writing code in scripting and command languages, Thrash Metal music and playing electric guitar.

Copyrights

©Copyright, 2018 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.

Citation

Cite this article as:

Wojnowski, Sylwester. "Sorting objects by their property in PHP." From sWWW - Code For The Web . https://wojnowski.net.pl//main/index/sorting-objects-by-their-property-in-php