views:

396

answers:

2

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.

+6  A: 

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;
cletus
Yes this is probably the best way. I'm probably thinking too hard about it.
tamewhale
+2  A: 

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.

Gordon
Both good answers. The sort was something I had in mind but it seemed like overkill.
tamewhale
@tamewhale Thanks. I did a very superficial benchmark with 24 animals and `unset` is really the fastest. It is 10 times faster than `array_shift` and 300 times faster than `uksort`.
Gordon