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

前端 未结 8 2289
一整个雨季
一整个雨季 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:18

    Since any numeric key would be re-indexed with array_unshift (as noted in the doc), it's better to use the + array union operator to move an item with a certain key at the first position of an array:

    $item = $arr[$key];
    unset($arr[$key]);
    $arr = array($key => $item) + $arr;
    
    0 讨论(0)
  • 2020-12-18 20:23

    No need to unset keys. To keep it short just do as follow

    //appending $new in our array 
    array_unshift($arr, $new);
    //now make it unique.
    $final = array_unique($arr);
    

    Demo

    0 讨论(0)
  • 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"]
    
    0 讨论(0)
  • 2020-12-18 20:25
    $tgt = 10;
    $key = array_search($tgt, $arr);
    for($i=0;$i<$key;$i++)
    {
       $temp = $arr[$i];
       $arr[$i] = $tgt;
       $tgt = $temp;
    }
    

    After this simple code, all you need to do is display the re-arranged array. :)

    0 讨论(0)
  • 2020-12-18 20:32

    Use array_unshift:

    $new_value = $arr[n];
    unset($arr[n]);
    array_unshift($arr, $new_value);
    
    0 讨论(0)
  • 2020-12-18 20:40
    <?php
    $key = 10;
    $arr = array(0,1,2,3);
    array_unshift($arr,$key);
    var_dump($arr) //10,0,1,2,3
    ?>
    
    0 讨论(0)
提交回复
热议问题