I have an array:
$array = array(
'a' => 'val1',
'b' => 'val2',
'c' => 'val3',
'd' => 'val4'
);
How do I swap any two elements by their keys (e.g. a
and d
) to produce this array:
$array = array(
'd' => 'val4',
'b' => 'val2',
'c' => 'val3',
'a' => 'val1'
);
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.