Shift one value of array values to the beginning Given an integer $value in the range of 1, 2, 3, I want to get an array that starts with $value and proceeds with the remaining two integers from above in arbitrary order. The best I could think of was doing something like this:

switch ($value) {
      case '1':
        $array = [1,2,3];
        break;

      case '2':
        $array = [2,1,3];
        break;

      case '3':
        $array = [3,1,2];
        break;
    }


Is there a shorter and more beautiful way of doing that? Something like that:

$array = push_to_top_of_array($value,[1,2,3]);
Is there a shorter and more beautiful way of doing that?



shorter: yes
more beautiful: well, that sounds subjective... you can be the judge of the approaches below.


One approach would be to take off the value using $index with array_splice() and then put it (the first element from that spliced array) at the beginning using array_unshift():

$array = [1, 2, 3];
array_unshift($array, array_splice($array, $value - 1, 1)[0]);


See it demonstrated in this playground example.

Another approach would be to merge the spliced array and the original array using array_merge():

$array = [1, 2, 3];
$array = array_merge(array_splice($array, $value - 1, 1), $array);


See it demonstrated in this playground example.