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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With