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

后端 未结 5 677
独厮守ぢ
独厮守ぢ 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

    I really like @Gordon's answer above for it's elegance as a one liner, but it only works if the key is at the beginning. Here's another one liner that will work for a key in any position:

    $arr = array('monkey' => 1, 'giraffe' => 2, 'lion' => 3);
    $arr += array_splice($arr,array_search('giraffe',array_keys($arr)),1);
    

    EDIT: Beware, this fails with numeric keys.

提交回复
热议问题