Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

asaketr64x's avatar

usort is a PHP function with spooky behavior ?

As far as the php docs are concerned in the method The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. But here is how I am using it with my posts

      foreach ($actualPosts as $post) {

            $post->sorter = [
                'sorter_date_time' => $post->created_at->diffForHumans(),
                'is_shared' => 'false',
                'post_sharer' => null
            ];

            
        }


In the above code I set the sorter_date_time to be string And then I use it inside usort

      usort($actualposts, function ($post1, $post2) {
            return $post2->sorter['sorter_date_time'] > $post1->sorter['sorter_date_time'];
        });

AND IT GIVES THE DESIRED RESULT!!.It gives the most recently created posts . How is this possible if I am using a string for comparison inside usort and not an integer?

0 likes
6 replies
Snapey's avatar

its comparing digits up to the first non-number

  • 3 days ago
  • 5 days ago
  • 8 days ago

but will probably fail on '10 days ago' and '1 month ago'

Why are you doing this - it seems a strange way of sorting...

asaketr64x's avatar

@Snapey if I use $post->created_at->toDateTimeString(). Will it work. cuz it returns the date-time in **Y-m-d H:i:s 00:00:00** format?If not then how can I change the time into integer to make it work?Thanks for the help!(Its indeed a strange way of sorting..lol....not until u see the entire code.)

Snapey's avatar
'sorter_date_time' => $post->created_at->timestamp;
1 like
topvillas's avatar

created_at will already be a Carbon instance so it's as simple as ...

created_at->timestamp
1 like

Please or to participate in this conversation.