如何用数组交换数组中的两个值?

For example i have an array like this $array = ('a' => 2, 'b' => 1, 'c' => 4); and i need to swap a with c to get this $array = ('c' => 4, 'b' => 1, 'a' => 2);. Wht is the best way for doing this without creating new array? I know that it is possible with XOR, but i also need to save indexes.

If you want to purely swap the first and the last positions, here's one way to do it:

$first = array(key($array) => current($array)); // Get the first key/value pair
array_shift($array); // Remove it from your array

end($array);
$last = array(key($array) => current($array)); // Get the last key/value pair
array_pop($array); // Remove it from the array

$array = array_merge($last, $array, $first); // Put it back together

Gives you:

Array
(
    [c] => 4
    [b] => 1
    [a] => 2
)

Working example: http://3v4l.org/r87qD

Update: And just for fun, you can squeeze that down quite a bit:

$first = array(key($array) => current($array));
$last = array_flip(array(end($array) => key($array)));
$array = array_merge($last, array_slice($array,1,count($array) - 2), $first);

Working example: http://3v4l.org/v6R7T

Update 2:

Oh heck yeah, we can totally do this in one line of code now:

$array = array_merge(array_flip(array(end($array) => key($array))), array_slice($array,1,count($array) - 2), array_flip(array(reset($array) => key($array))));

Working example: http://3v4l.org/QJB5T

That was fun, thanks for the challenge. =)

array_splice would be perfect, but unfortunately it doesn't preserve the keys in the inserted arrays. So you'll have to resort to a little more manual slicing and dicing:

function swapOffsets(array $array, $offset1, $offset2) {
    list($offset1, $offset2) = array(min($offset1, $offset2), max($offset1, $offset2));

    return array_merge(
        array_slice($array, 0, $offset1, true),
        array_slice($array, $offset2, 1, true),
        array_slice($array, $offset1 + 1, $offset2 - $offset1 - 1, true),
        array_slice($array, $offset1, 1, true),
        array_slice($array, $offset2 + 1, null, true)
    );
}