$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 array