I have an array:
$array = array('a' => 'val1', 'b' => 'val2', 'c' => 'val3', 'd' => 'val4');
How do I swap any two keys round so the array is in a different order? E.g. to produce this array:
$array = array('d' => 'val4', 'b' => 'val2', 'c' => 'val3', 'a' => 'val1');
Thanks :).
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
Not ideal but does what you want to do:
$array = array('a' => 'val1', 'b' => 'val2', 'c' => 'val3', 'd' => 'val4');
$keys = array_keys($array);
swap($keys, 0, 3);
$values = array_values($array);
swap($values, 0, 3);
print_r(array_combine($keys, $values)); // Array ( [d] => val4 [b] => val2 [c] => val3 [a] => val1 )
function swap (&$arr, $e1, $e2)
{
$temp = $arr[$e1];
$arr[$e1] = $arr[$e2];
$arr[$e2] = $temp;
}
Of course you should also check if both indexes are set in swap
function (using isset
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With