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.
You can use the returned function array. shift() as input to the function array. push().
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.
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.
The push() method is used for adding an element to the end of an array.
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;
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.
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