0

Suppose, I have an array

$array1 = array(10, 20);

and another array of same values as above

$array2 = array(10, 20);

I want to combine these two arrays and generate an array with unique key and value pair. I want $array3 output to be like this:

$array3 = array(10 => 20, 20 => 10)

I tried shuffling the second array ($array2), sometimes it gives me the same values as first one($array1). And my $array3 output is:

$array3 = array(10 => 10, 20 => 20)
4
  • Why 10 => 20, 20 => 10? Commented May 21, 2014 at 5:23
  • will there always be only two pairs of key and value? Commented May 21, 2014 at 5:23
  • @nbin No. Values can be upto 3 or 4 for an array. But two array values are always same. I want to generate an array with unique pair of keys and values. No key and value should be the same. Commented May 21, 2014 at 5:26
  • @Wahyu Kristianto I'm working on a custom application in which a users' file needs to be exchanged with some other user. Commented May 21, 2014 at 5:31

1 Answer 1

1
array_combine($array1, array_reverse($array2));

That will achieve the $array3 that you specified in the example you provided, but in general will not work unless $array1 and $array2 have the same number of values.

I'm a little confused about what you really need. Can you provide another example with more keys / values?

Sign up to request clarification or add additional context in comments.

5 Comments

I have two arrays of same values. $array1 = array(10, 20, 30, 40, 50); $array2 = array(10, 20, 30, 40, 50); Two arrays will always have same number of values. I want a new array, which new array key and value should not be the same.
Your algorithm is good. However it fails at $array1 = array(10, 20, 30); $array2 = array(10, 20, 30);
then pair of keys and values doesnt matter as long as they are not same. yah?
then above answer does your job.
ideone.com/9SHyqN - It does not fail for the example you gave in your comments. Can you provide any more explanation on how it fails?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.