Home    Articles


Sort days of the week in array with php [CODE]


Often we need to sort days of the week to be listed into an <select> html tag as it should...i meant ordered. Monday or Sunday first...etc. But there is no sort function to do so, this is why we need to do it.

Probably this algorithm is not the best way to sort the days of the week in array but will do the job.

Have a look in the code, read comments and you will understand the algorithm.

Here is how you can sort an array that contains days of the week.

#default array
$daysOfWeek = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
#your array
$days = array('Tuesday','Sunday','Thursday','Monday');
#create a new array with key association property
$daysAux = array();
foreach($days as $k=>$v) {
	$key = array_search($v, $daysOfWeek);
	if($key !== FALSE) {
		$daysAux[$key] = $v;
# array before sort
echo '<pre/>';print_r($daysAux);
$days = $daysAux;
#final result
echo '<pre/>';print_r($days);exit;