I have a PHP array similar to this:
0 => "red",
1 => "green",
2 => "blue",
3 => "yellow"
I want to move yellow to index 0. How do I do this?
Edit: My question is how do I move any one of these elements to the beginning? How would I move green to index 0, or blue to index 0? This question is not exclusively about moving the last element to the beginning.
The array_keys() function returns an array containing the keys.
The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array. Tip: You can add one value, or as many as you like.
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.
This seems like the simplest way to me. You can move any position to the beginning, not just the last (in this example it moves blue to the beginning).
$colours = array("red", "green", "blue", "yellow");
$movecolour = $colours[2];
unset($colours[2]);
array_unshift($colours, $movecolour);
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