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;
If you have an associative array you can use array_merge.
$arr = array_merge([$key=>$arr[$key]], $arr);
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"]
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);
array_unique threw an error. ("Uncaught Error: Object of class [myClassName] could not be converted to string.") I switched to the array_unshift method described in Yan Berk's answer, and it worked perfectly.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;
<?php
$key = 10;
$arr = array(0,1,2,3);
array_unshift($arr,$key);
var_dump($arr) //10,0,1,2,3
?>
if you have numeric keys they will be re-indexed starting from 0 if you array_merge them. To avoid it use + operator:
[2 => 'blue']
+
[31 => 'red',
2 => 'blue',
254 => 'black'];
this will give
[2 => 'blue',
31 => 'red',
254 => 'black']
$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. :)
array_search() is a short-circuiting loop. for() is another loop. If the $key in the original array is already in the last position, this snippet performs two complete loops. Since the invention of symmetric array destructuring syntax, there is no need for a $temp variable. Maybe put a condition inside the for loop instead of calling array_search(). This answer is ...not awesome.
$arrremains the same$arr[n] = n