phparrayssorting

Move nominated value of a flat array to become the first element


$key = "cat"
$array = array(
    'dog',
    'bird', 
    'cat',
    'moon'
);

Need order like this (by key): cat, dog, bird, moon.

$key = "cat" , so string "cat" need to be first element of array. How to do that?


Solution

  • You're not actually sorting, just moving something in the array to the beginning. It might be simpler but here is one way:

    array_unshift($array, current(array_splice($array, array_search($key, $array), 1)));