66

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.

4 Answers 4

129

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;
Sign up to request clarification or add additional context in comments.

Comments

13

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.

4 Comments

Both good answers. The sort was something I had in mind but it seemed like overkill.
@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.
Love the one liner - possibly not the most efficient but in most cases it will never matter and the elegance of the array_shift() approach makes it clean and readable.
The first solution with array_shift works only for 1st element of the array.
4

I really like @Gordon's answer for its elegance as a one liner, but it only works if the targeted key exists in the first element of the array. Here's another one-liner that will work for a key in any position:

$arr = ['monkey' => 1, 'giraffe' => 2, 'lion' => 3];
$arr += array_splice($arr, array_search('giraffe', array_keys($arr)), 1);

Demo

  • Beware, this fails with numeric keys because of the way that the array union operator (+=) works with numeric keys (Demo).
  • Also, this snippet assumes that the targeted key is guaranteed to exist in the array. If the targeted key does not exist, then the result will incorrectly move the first element to the end because array_search() will return false which will be coalesced to 0 by array_splice() (Demo).

Comments

-1

You can implement some basic calculus and get a universal function for moving array element from one position to the other.

For PHP it looks like this:

function magicFunction ($targetArray, $indexFrom, $indexTo) { 
    $targetElement = $targetArray[$indexFrom]; 
    $magicIncrement = ($indexTo - $indexFrom) / abs ($indexTo - $indexFrom); 

    for ($Element = $indexFrom; $Element != $indexTo; $Element += $magicIncrement){ 
        $targetArray[$Element] = $targetArray[$Element + $magicIncrement]; 
    } 

    $targetArray[$indexTo] = $targetElement; 
}

Check out "moving array elements" at "gloommatter" for detailed explanation.

http://www.gloommatter.com/DDesign/programming/moving-any-array-elements-universal-function.html

1 Comment

The question was about moving a single element from an associative array to the end of that array. This code does not have anything to do with that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.