Moving array element to top in PHP

后端 未结 5 1977
陌清茗
陌清茗 2020-12-05 15:27
$arr = array(
    \'a1\'=>\'1\',
    \'a2\'=>\'2\'
);

I need to move the a2 to the top, as well as keep the a2 as a key how woul

5条回答
  •  半阙折子戏
    2020-12-05 16:03

    Here's a simple one liner to get this done with array_splice() and the union operator:

    $arr = array('a1'=>'1', 'a2'=>'2', 'a3' => '3');
    $arr = array_splice($arr,array_search('a2',array_keys($arr)),1) + $arr;
    

    Edit:

    In retrospect I'm not sure why I wouldn't just do this:

    $arr = array('a2' => $arr['a2']) + $arr;
    

    Cleaner, easier and probably faster.

提交回复
热议问题