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

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

    Something like this should work. Check if the array key exists, get its value, then unset it, then use array_unshift to create the item again and place it at the beginning.

    if(in_array($key, $arr)) {
        $value = $arr[$key];
        unset($arr[$key]);
        array_unshift($arr, $value);
    }
    
    0 讨论(0)
  • 2020-12-18 20:44
    $arr[0]=0;
    $arr[1]=1;
    $arr[2]=2;
    $arr[3]=10;
    
    
    $tgt = 10;
    $key = array_search($tgt, $arr);
    unset($arr[$key]);
    array_unshift($arr, $tgt);
    
    // var_dump( $arr );
    array
    0 => int 10
    1 => int 0
    2 => int 1
    3 => int 2
    
    0 讨论(0)
提交回复
热议问题