Sorting objects by their property in PHP

Sorting objects by their property in PHP

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

Sorting objects by their property..

Prepare some sample objects:

$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

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

Use usort PHP function.

Sort by string

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

This post was updated on 06 Oct 2021 20:32:14

Tags:  php ,  sort 

Author, Copyright and citation


Sylwester Wojnowski

Author of the this article - Sylwester Wojnowski - is a sWWW web developer. He has been writing computer code for the websites and web applications since 1998.


©Copyright, 2022 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!