Reputation:
I have a very simple array like this:
Array ( [friend_id] => 180 [user_id] => 175 )
What I want to do is just to switch the values, in order to be come this:
Array ( [friend_id] => 175 [user_id] => 180 )
Is there any elegant NON STATIC way in PHP to do it?
Upvotes: 0
Views: 390
Reputation: 13
How about using array_flip?
array array_flip ( array $trans )
$myar = array('apples', 'oranges', 'pineaples'); print_r($myar);
print_r(array_flip($myar));
Array
(
[0] => apples
[1] => oranges
[2] => pineaples
)
Array
(
[apples] => 0
[oranges] => 1
[pineaples] => 2
)
Upvotes: 0
Reputation: 32973
A bit longish, but I think it satisfies you requirements for 2 element arrays, just as you used in your example:
// your input array = $yourarray;
$keyarray = array_keys($yourarray);
$valuearray = array_values($yourarray);
/// empty input array just to make sure
$yourarray = array();
$yourarray[$keyarray[0]] = $valuearray[1];
$yourarray[$keyarray[1]] = $valuearray[0];
Basically Orangepill's answer done manually...
Upvotes: 0
Reputation: 3424
$tmp = $array['user_id'];
$array['user_id'] = $array['friend_id'];
$array['friend_id'] = $tmp;
Upvotes: -1
Reputation: 24655
you can use array_combine and array_reverse
$swapped = array_combine(array_keys($arr), array_reverse(array_values($arr)));
Upvotes: 3
Reputation: 360772
No. Use a temporary value:
$temp = $array['friend_id'];
$array['friend_id'] = $array['user_id'];
$array['user_id'] = $temp;
Upvotes: 2