punnu punnu - 3 months ago 26
PHP Question

Sort array of weekdays with current day as 1st element in array

I want to sort an array of weekdays with current day being the 1st element in the array.

Current day :

$day=date("l");


The $day gives me Thursday

Input:

Array
(
[0] => Wednesday 9:30AM-6PM
[1] => Thursday 9:30AM-9PM
[2] => Friday 9:30AM-7PM
[3] => Saturday 9AM-6PM
[4] => Sunday 10AM-6PM
[5] => Monday 9:30AM-6PM
[6] => Tuesday 9:30AM-6PM
)


Output:

Array
(
[0] => Thursday 9:30AM-9PM
[1] => Friday 9:30AM-7PM
[2] => Saturday 9AM-6PM
[3] => Sunday 10AM-6PM
[4] => Monday 9:30AM-6PM
[5] => Tuesday 9:30AM-6PM
[6] => Wednesday 9:30AM-6PM
)

Answer

You can do it like below:-

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$day=date("l");

$data = Array
(
  '0' => 'Wednesday 9:30AM-6PM',
  '1' => 'Thursday 9:30AM-9PM',
  '2' => 'Friday 9:30AM-7PM',
  '3' => 'Saturday 9AM-6PM',
  '4' => 'Sunday 10AM-6PM',
  '5' => 'Monday 9:30AM-6PM',
  '6' => 'Tuesday 9:30AM-6PM'
);
$new_date_array = array();
$count = count($data);
foreach($data as $key=> $dat){
   if(strpos($dat, $day) !== false){ // get the key where input day matched
        for ($i =$key; $i<$count;$i++){ // add next all records to the new array till the end of the original array
            if(isset($data[$i])){
                $new_date_array[] = $data[$i];
            }

        }
        for ($j=0; $j<=$key-1;$j++){ // add previous one before the matched key to the new array
            if(isset($data[$j])){
                $new_date_array[] = $data[$j];
            }

        }
   }
}

echo "<pre/>";print_r($new_date_array);

Output:-

Array
(
    [0] => Thursday 9:30AM-9PM
    [1] => Friday 9:30AM-7PM
    [2] => Saturday 9AM-6PM
    [3] => Sunday 10AM-6PM
    [4] => Monday 9:30AM-6PM
    [5] => Tuesday 9:30AM-6PM
    [6] => Wednesday 9:30AM-6PM
)

One more output (when i changed day for comparison manually):-https://eval.in/633102

Comments