The following PHP function could swap the array elements by the array keys.
function array_swap_assoc($key1, $key2, $array) {
$newArray = array ();
foreach ($array as $key => $value) {
if ($key == $key1) {
$newArray[$key2] = $array[$key2];
} elseif ($key == $key2) {
$newArray[$key1] = $array[$key1];
} else {
$newArray[$key] = $value;
}
}
return $newArray;
}
try it out.
<?php
$temp = array('a' => 'A', 'b' => 'B');
$temp = array_swap_assoc('a', 'b', $temp);
print_r($temp);
// $temp => array('b' => 'B', 'a' => 'A');
?>
Done =)
Reference: Stack Overflow – Switch two items in associative array PHP

Shouldn’t it be $newArray[$key] = $array[$key2]; ?
LikeLike
Depends on what you want to end up with, in this example, it doesn’t change the key value pair but just swap their positions.
Your comment will result in
$temp => array('a' => 'B', 'b' => 'A');is that what u want to do?
LikeLike
wtf? foreach?
function array_swap_assoc($key1, $key2, $array) { if (isset($array[$key1], $array[$key2])) { $temp = $array[$key1]; $array[$key1] = $array[$key2]; $array[$key2] = $temp; } return $array; }LikeLiked by 1 person