Swap two key/value pairs in an array
I thought there would be really simple answer by now, so I'll throw mine in the pile:
// Make sure the array pointer is at the beginning (just in case)
reset($array);
// Move the first element to the end, preserving the key
$array[key($array)] = array_shift($array);
// Go to the end
end($array);
// Go back one and get the key/value
$v = prev($array);
$k = key($array);
// Move the key/value to the first position (overwrites the existing index)
$array = array($k => $v) + $array;
This is swapping the first and last elements of the array, preserving keys. I thought you wanted array_flip()
originally, so hopefully I've understood correctly.
Demo: http://codepad.org/eTok9WA6
Best A way is to make arrays of the keys and the values. Swap the positions in both arrays, and then put 'em back together.
function swapPos(&$arr, $pos1, $pos2){
$keys = array_keys($arr);
$vals = array_values($arr);
$key1 = array_search($pos1, $keys);
$key2 = array_search($pos2, $keys);
$tmp = $keys[$key1];
$keys[$key1] = $keys[$key2];
$keys[$key2] = $tmp;
$tmp = $vals[$key1];
$vals[$key1] = $vals[$key2];
$vals[$key2] = $tmp;
$arr = array_combine($keys, $vals);
}
Demo: http://ideone.com/7gWKO