27

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;
5
  • 1
    In the example, you're not "choosing element by key". You're just inserting an arbitrary value to the beginning of the array. I think this might confuse other people Commented Jul 28, 2012 at 19:00
  • 2
    @galymzhan I think it's implied that $arr[10] was previously 10, and now it goes from $arr[9]=9 to $arr[10]=11. I agree that the example doesn't illustrate this clearly. It would be better to a) show the array element that's being "moved", and b) use different element values so it's harder to confuse a key with its value. Commented Jul 28, 2012 at 19:02
  • It seems the best will be the good old way with a temporary array and cycle Commented Jul 28, 2012 at 19:04
  • @octern Yes, I think you're right, because size of $arr remains the same $arr[n] = n Commented Jul 28, 2012 at 19:05
  • Topically related: Move associative array element to beginning of array Commented Mar 11 at 1:45

10 Answers 10

44

Use array_unshift:

$new_value = $arr[n];
unset($arr[n]);
array_unshift($arr, $new_value);
Sign up to request clarification or add additional context in comments.

3 Comments

The same array, it looks as if it doesn't change keys
oops edit: I was printing out keys, let me try once more. Of course it works. I'm sorry for the confusion
Glad it helped. Notice that the array needs to be reindexed afterwards. Read here how to do this: stackoverflow.com/questions/591094/…
16

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"]

2 Comments

Doesn't this code copy the element instead of moving it?
@Gonzalingui, You may be right! Doesn't it depends on the value in the array, though? If it is scalar, it might copy it but if it is a reference value then wouldn't it only copy the reference and not the value? (I could be wrong, but I don't think the OP was asking more about changing the value in an array variable than the underlying computer science fundamentals of moving versus copying a value in held in memory. :) )
14

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

2 Comments

This solution works only for arrays containing numbers and ignoring it's key. Also, it's inserting a new element, but the question asks how to move an existent array item to the first position. It clearly doesn't answer the question.
Caution: If you're trying to move an element in an array of OBJECTS, this method may not work for you. In my case, the call to 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.
7

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);
}

Comments

6

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;

Comments

4
<?php
$key = 10;
$arr = array(0,1,2,3);
array_unshift($arr,$key);
var_dump($arr) //10,0,1,2,3
?>

1 Comment

This prepends the chosen element, but it doesn't reference it by key and remove it from elsewhere in the array.
3
$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

Comments

1

For example, so: $arr = [$key => $arr[$key]] + $arr;

Comments

1

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']

1 Comment

This answer explains @MaximMandrik's earlier answer.
0
$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. :)

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.