1

I want to sort or reorder the array element based on start on value.

My array:

[
    0 => 'Sun',
    1 => 'Mon',
    2 => 'Tue',
    3 => 'Wed',
    4 => 'Thu',
    5 => 'Fri',
    6 => 'Sat'
]

$startOn = 3;

Expected Output :

[
    3 => 'Wed',
    4 => 'Thu',
    5 => 'Fri',
    6 => 'Sat',
    0 => 'Sun',
    1 => 'Mon',
    2 => 'Tue',
]

I tried using uksort but it does not return the expected output.

uksort($weekDays, function ($a, $b) use ($startOn) {
    return $startOn-$a;
});

Current output :

[
    3 => 'Wed'
    4 => 'Thu'
    5 => 'Fri'
    6 => 'Sat'
    2 => 'Tue'
    1 => 'Mon'
    0 => 'Sun'
]
2
  • 3
    That's not sorting. Just slice subarray and append it to the end. Commented Sep 17, 2019 at 5:33
  • You can use ($k + 7 - $startOn) % 7 as the key in uksort, check my answer Commented Sep 17, 2019 at 6:13

4 Answers 4

1

You can use foreach

$start = 3;
$r1 = $r2 = [];
foreach($a as $k => $v){
  ($k >= $start) ? ($r1[$k]=$v) : ($r2[$k]=$v);
}
$r = $r1 + $r2;
print_r($r);

Working example :- https://3v4l.org/1KDoR

Sign up to request clarification or add additional context in comments.

1 Comment

Method 1 - It's ok but when $startOn = 0 that error and Method 2 - when $startOn = 0 that time remove the last element
1

As the array_slice() code has been removed from the other answer, thought I would add my version here.

The main thing is to set the fourth parameter to true so that it retains the key...

$weekDays = array_slice($weekDays, $startOn, null, true) 
        + array_slice($weekDays, 0, $startOn, true);

Comments

1

With uksort, check the Demo

$startOn = 3;
uksort($array,function($a,$b)use($startOn){return ($a + 7 - $startOn) % 7 - ($b + 7 - $startOn) % 7;});
print_r($array);

Comments

1

Here is working solution,

$k = array_search(3, array_keys($arr));
$arr = array_slice($arr,$k,null,true) + array_slice($arr,0,$k,true);
print_r($arr);

Demo.

Output:-

Array
(
    [3] => Wed
    [4] => Thu
    [5] => Fri
    [6] => Sat
    [0] => Sun
    [1] => Mon
    [2] => Tue
)

array_search — Searches the array for a given value and returns the first corresponding key if successful

array_slice — Extract a slice of the array

Note:

array_slice() will reorder and reset the integer array indices by default. This behaviour can be changed by setting preserve_keys to TRUE. String keys are always preserved, regardless of this parameter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.