1

I want to randomly shuffle the keys and values of a php array. I've already found solution to shuffle the order, but I want to shuffle the keys and values themselves.

The array array('yes' => 'oui', 'no' => 'non', 'hello' => 'bonjour') would for example become array('oui' => 'yes, 'no' => 'non', 'bonjour' => 'hello'). Note that the first and last value have randomly swapped key and value.

I know you can use array_flip to flip the keys and values in an array. But this flips all keys and values, while I want to randomly flip a few keys and values. How would I do this?

2
  • You can split the array into N arrays with random lengths, then do the array_flip on N-X of them and then merge them and shuffle the merged array once again? Commented Nov 15, 2017 at 11:08
  • may be, so: eval.in/900559 Commented Nov 15, 2017 at 11:21

2 Answers 2

1
$array = array('yes' => 'oui', 'no' => 'non', 'hello' => 'bonjour');

foreach($array as $key => $value) {
    if (0 === rand(0,1)) {
        $array[$value] = $key;
        unset($array[$key]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1
$array = array('yes' => 'oui', 'no' => 'non', 'hello' => 'bonjour');

// Run it in a foreach loop
foreach ($array as $key => $val){
    // rand(0, 1) will return either 0 or 1
    // It's up to you which value you want to set as anchor.
    if (rand(0, 1) === 0){
        // Set the value as key,
        // then set the key as value.
        $array[$val] = $key;

        // Delete the original one.
        unset($array[$key]);
    }
}

Comments

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.