How do I move an array element with a known key to the end of an array in PHP?

后端 未结 5 678
独厮守ぢ
独厮守ぢ 2020-12-03 04:19

Having a brain freeze over a fairly trivial problem. If I start with an array like this:

$my_array = array(
                  \'monkey\'  => array(...),
          


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-03 05:04

    array_shift is probably less efficient than unsetting the index, but it works:

    $my_array = array('monkey' => 1, 'giraffe' => 2, 'lion' => 3);
    $my_array['monkey'] = array_shift($my_array);
    print_r($my_array);
    

    Another alternative is with a callback and uksort:

    uksort($my_array, create_function('$x,$y','return ($y === "monkey") ? -1 : 1;'));
    

    You will want to use a proper lambda if you are using PHP5.3+ or just define the function as a global function regularly.

提交回复
热议问题