Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move Value in PHP Array to the Beginning of the Array

Tags:

arrays

php

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.

like image 754
Jarred Avatar asked Nov 08 '10 17:11

Jarred


People also ask

What is Array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

How do I add to 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. Tip: You can add one value, or as many as you like.

How do you move an element to the first position of 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.


1 Answers

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);
like image 163
SharpC Avatar answered Nov 16 '22 00:11

SharpC