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


usort($to_be_sorted,function($a,$b){
  return $a -> num > $b -> num;
}); 

Use usort PHP function.

Sort by string


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

Author

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.

Copyrights

©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.

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

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!