$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?
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)));
array_search()
finds the index of the element that contains $key
array_splice()
removes that elementarray_unshift()
prepends that element to the arrayAll the above solutions will work fine with the provided input array
$array = array('dog','bird', 'cat','moon');
However if the input array in an associative array, then above solutions will not work. See the changed input array below:
$array = array('frist' => 'foo', 'dog','bird', 'cat','moon', 'cat');
It will be handy to use the following function in case of performance. It does not have overhead of calling too many builtin PHP array functions. Moreover it will work both sequential and associative PHP arrays. See the code segment below:
function moveToTop($array, $key){ foreach ($array as $index => $value) ($value != $key) ? $newArray[$index] = $value : ''; array_unshift($newArray, $key); return $newArray; }
moveToTop($array, $key)
Array ( [0] => cat [frist] => foo [1] => dog [2] => bird [3] => moon )