Reputation: 607
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?
Upvotes: 1
Views: 229
Reputation: 7080
$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]);
}
}
Upvotes: 1
Reputation: 456
$array = array('yes' => 'oui', 'no' => 'non', 'hello' => 'bonjour');
foreach($array as $key => $value) {
if (0 === rand(0,1)) {
$array[$value] = $key;
unset($array[$key]);
}
}
Upvotes: 1