0

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?

3
  • What do you mean by "non static"? Commented Jul 19, 2013 at 15:11
  • By non-static, do you mean that you always want the friend_id switched with the user_id? Commented Jul 19, 2013 at 15:11
  • No I mean that it can do the job without having to declare the indexes Commented Jul 19, 2013 at 15:11

5 Answers 5

3

you can use array_combine and array_reverse

$swapped = array_combine(array_keys($arr), array_reverse(array_values($arr)));
Sign up to request clarification or add additional context in comments.

Comments

2

No. Use a temporary value:

$temp = $array['friend_id'];
$array['friend_id'] = $array['user_id'];
$array['user_id'] = $temp;

3 Comments

Odd, imo this answer is as wrong as the one scoring -1, yet it gets 2 upvotes.
@fvu: uh, perhaps you should start looking at timestamps. at the time I posted this, the OP hadn't yet posted his "without indexes" comment.
I understand your reasoning, I was merely commenting on what I perceive as intriguing voting behavior.
0

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...

Comments

0

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
)

Comments

-1
$tmp = $array['user_id'];
$array['user_id'] = $array['friend_id'];
$array['friend_id'] = $tmp;

1 Comment

Not the downvoter, but in his clarification OP says you don't know the indexes. Your technique only works when the indexes are known.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.