Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array contains some dates by days order like sunday, monday etc. in php

Tags:

arrays

date

php

I have an array with 7 dates.

$dates = array(
'2018-03-07', //Wednesday
'2018-03-08', //Thursday
'2018-03-09', //Friday
'2018-03-10', //Saturday
'2018-03-11', //Sunday
'2018-03-12', //Monday
'2018-03-13', //Tuesday
);

I want to sort the above array by day wise (Sunday to Saturday order).

The expected output is,

 $dates = array(
'2018-03-11', //Sunday
'2018-03-12', //Monday
'2018-03-13', //Tuesday
'2018-03-07', //Wednesday
'2018-03-08', //Thursday
'2018-03-09', //Friday
'2018-03-10', //Saturday
);

How to sort like this? Please help me.

like image 874
Arya Avatar asked Nov 29 '25 16:11

Arya


1 Answers

You could use usort() and date('w'), to sort your array using the "Numeric representation of the day of the week"

$dates = array(
'2018-03-07', //Wednesday
'2018-03-08', //Thursday
'2018-03-09', //Friday
'2018-03-10', //Saturday
'2018-03-11', //Sunday
'2018-03-12', //Monday
'2018-03-13', //Tuesday
);

usort($dates, function($a, $b) {
    return date('w',strtotime($a)) - date('w',strtotime($b)) ;
});

print_r($dates);

Outputs :

Array
(
    [0] => 2018-03-11
    [1] => 2018-03-12
    [2] => 2018-03-13
    [3] => 2018-03-07
    [4] => 2018-03-08
    [5] => 2018-03-09
    [6] => 2018-03-10
)

date('w') returns : 0 (for Sunday) through 6 (for Saturday).

like image 53
Syscall Avatar answered Dec 02 '25 06:12

Syscall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!