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

PhpArraysSorting

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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;

Solution 2 - Php

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.

Solution 3 - Php

I really like @Gordon's answer above for it's elegance as a one liner, but it only works if the key is at the beginning. Here's another one liner that will work for a key in any position:

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

EDIT: Beware, this fails with numeric keys.

Solution 4 - Php

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

Solution 5 - Php

based on @cletus answer I use it in a foreach to delete duplicates of a specific element and move first occurence of it to the end the array like this :

foreach($ievent as $k => $ev) {
    
    //make other operations in my foreach 			
    ...
					
	//Delete duplicate CLOSE event
	if($ev['event'] == 'close') {
		if(!$close) {
			$close = $ievent[$k];
        }
		unset($ievent[$k]);
	}			
}
        		
//Add first 'close' element to end of array
$ievent[] = $close;

Solution 6 - Php

Doing this conditionally inside a foreach loop using the array index:

$i = 0;
foreach( $items as $item ) {
    if ( $item->Value === 0 ) { // the condition I'm using, you can do whatever
        $item_to_move = $items[$i]; // pick out our item
        unset( $items[$i] ); // take it out of the array
        array_push( $items, $item_to_move); // re-add it (at the end)
    }
    $i++;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontamewhaleView Question on Stackoverflow
Solution 1 - PhpcletusView Answer on Stackoverflow
Solution 2 - PhpGordonView Answer on Stackoverflow
Solution 3 - PhpEaten by a GrueView Answer on Stackoverflow
Solution 4 - PhpAndreaView Answer on Stackoverflow
Solution 5 - PhpMelomanView Answer on Stackoverflow
Solution 6 - PhpSimon CView Answer on Stackoverflow