Order array by days of the week in PHP

Here we have an array of values that has day of the week as a value. what we need to achieve is sort this array from Monday to Sunday.

We will create weekdays array with the order of the days we want. If you want Sunday on first you can change the order of $weekdays array.

We will be sorting the $list using uasort . We get the index of each day using array_search

$index = array_search('Wednesday',$weekdays); // Output is 2

We are using spaceship operator ( <=> ) to compare indexes. It is introduced in PHP 7 . It is used to compare two expressions. It returns -1, 0 or 1 when first expression is respectively less than, equal to, or greater than second expression.

Completed code is below. let me know your suggestions in comments.

$list = [["day_of_week" => "Monday", "time" => "12:30 - 13:00"], ["day_of_week" => "Wednesday", "time" => "12:30 - 13:00"], ["day_of_week" => "Sunday", "time" => "12:30 - 13:00"], ["day_of_week" => "Tuesday", "time" => "12:30 - 13:00"], ["day_of_week" => "Thursday", "time" => "20:00 - 21:30"], ["day_of_week" => "Friday", "time" => "19:30"]];

$weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

uasort($list, function ($a, $b) use ($weekdays) {
	$aidx = array_search($a['day_of_week'], $weekdays);
	$bidx = array_search($b['day_of_week'], $weekdays);
	return $aidx <=> $bidx;
});