Move array item with certain key to the first posi

2020-02-12 01:58发布

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]=n;
$key=10;

Output:

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

标签: php arrays
8条回答
疯言疯语
2楼-- · 2020-02-12 02:05

Use array_unshift:

$new_value = $arr[n];
unset($arr[n]);
array_unshift($arr, $new_value);
查看更多
做自己的国王
3楼-- · 2020-02-12 02:08

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"]
查看更多
Root(大扎)
4楼-- · 2020-02-12 02:10

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;
查看更多
手持菜刀,她持情操
5楼-- · 2020-02-12 02:11

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

查看更多
成全新的幸福
6楼-- · 2020-02-12 02:12
$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
查看更多
家丑人穷心不美
7楼-- · 2020-02-12 02:17

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);
}
查看更多
登录 后发表回答