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;
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.
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.
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.
The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array.
Use array_unshift
:
$new_value = $arr[n];
unset($arr[n]);
array_unshift($arr, $new_value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With