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;
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;
Use
array_unshift
:Old question, and already answered, but if you have an associative array you can use array_merge.
EDITED (above to show PHP7+ notation, below is example)
The effective outcome of this operation
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:No need to unset keys. To keep it short just do as follow
Demo
Something like this should work. Check if the array key exists, get its value, then
unset
it, then usearray_unshift
to create the item again and place it at the beginning.