Moving array element to top in PHP

Here is a solution which works correctly both with numeric and string keys:

function move_to_top(&$array, $key) {
    $temp = array($key => $array[$key]);
    unset($array[$key]);
    $array = $temp + $array;
}

It works because arrays in PHP are ordered maps.
Btw, to move an item to bottom use:

function move_to_bottom(&$array, $key) {
    $value = $array[$key];
    unset($array[$key]);
    $array[$key] = $value;
}

Leave a Comment