Move array item with certain key to the first position in an array, PHP

前端 未结 8 2330
一整个雨季
一整个雨季 2020-12-18 19:54

What\'s the most elegant way in PHP to move an array element chosen by key to the first position?

Input:

$arr[0]=0;
$arr[1]=1;
$arr[2]=2;
....
$arr[n         


        
8条回答
  •  鱼传尺愫
    2020-12-18 20:24

    Old question, and already answered, but if you have an associative array you can use array_merge.

    $arr = array_merge([$key=>$arr[$key]], $arr);
    

    EDITED (above to show PHP7+ notation, below is example)

    $arr = ["a"=>"a", "b"=>"b", "c"=>"c", "d"=>"d"];
    $arr = array_merge(["c"=>$arr["c"]], $arr);
    

    The effective outcome of this operation

    $arr == ["c"=>"c", "a"=>"a", "b"=>"b", "d"=>"d"]
    

提交回复
热议问题