Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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;
like image 903
user965748 Avatar asked Jul 28 '12 18:07

user965748


People also ask

How do you move an element to the top of an array in PHP?

Here's a simple one liner to get this done with array_splice() and the union operator: $arr = array('a1'=>'1', 'a2'=>'2', 'a3' => '3'); $arr = array_splice($arr,array_search('a2',array_keys($arr)),1) + $arr; Edit: Cleaner, easier and probably faster.

How do I change the position of an array element in PHP?

We will use array_values() function to get all the values of the array and range() function to create an array of elements which we want to use as new keys or new index of the array (reindexing). Then the array_combine() function will combine both the array as keys and values.

How do you change the position of an item in an array?

To change the position of an element in an array:Use the splice() method to insert the element at the new index in the array. The splice method changes the original array by removing or replacing existing elements, or adding new elements at a specific index.

How do you insert an item at the beginning of an array in PHP?

The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array.


1 Answers

Use array_unshift:

$new_value = $arr[n];
unset($arr[n]);
array_unshift($arr, $new_value);
like image 147
Yan Berk Avatar answered Sep 19 '22 12:09

Yan Berk