Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I move an array element with a known key to the end of an array in PHP?

Having a brain freeze over a fairly trivial problem. If I start with an array like this:

$my_array = array(                   'monkey'  => array(...),                   'giraffe' => array(...),                   'lion'    => array(...) ); 

...and new elements might get added with different keys but always an array value. Now I can be sure the first element is always going to have the key 'monkey' but I can't be sure of any of the other keys.

When I've finished filling the array I want to move the known element 'monkey' to the end of the array without disturbing the order of the other elements. What is the most efficient way to do this?

Every way I can think of seems a bit clunky and I feel like I'm missing something obvious.

like image 311
tamewhale Avatar asked Mar 01 '10 22:03

tamewhale


People also ask

How do you move the first element of an array to the end of an array?

You can use the returned function array. shift() as input to the function array. push().

How do you move an element in an array?

Create a temp variable and assign the value of the original position to it. Now, assign the value in the new position to original position. Finally, assign the value in the temp to the new position.

How do I get the last key of an array?

You can use the end() function in PHP to get the last element of any PHP array. It will set the internal pointer to the last element of the array and return its value.

Which function is use to add the element to the end of an array?

The push() method is used for adding an element to the end of an array.


2 Answers

The only way I can think to do this is to remove it then add it:

$v = $my_array['monkey']; unset($my_array['monkey']); $my_array['monkey'] = $v; 
like image 92
cletus Avatar answered Oct 14 '22 15:10

cletus


array_shift is probably less efficient than unsetting the index, but it works:

$my_array = array('monkey' => 1, 'giraffe' => 2, 'lion' => 3); $my_array['monkey'] = array_shift($my_array); print_r($my_array); 

Another alternative is with a callback and uksort:

uksort($my_array, create_function('$x,$y','return ($y === "monkey") ? -1 : 1;')); 

You will want to use a proper lambda if you are using PHP5.3+ or just define the function as a global function regularly.

like image 39
Gordon Avatar answered Oct 14 '22 15:10

Gordon