1
Assuming I have one array in this way:
array(10, 11, 12, 13, 14, 15)
I’m trying to make a way to get as a result, a array with key-value pairs, but randomly without pairs being equal. For example:
Valid
array(
10 => 14,
11 => 12,
12 => 15,
13 => 10,
14 => 11,
15 => 13
)
Not valid
array(
10 => 14,
11 => 11, // Não pode
12 => 15,
13 => 10,
14 => 12,
15 => 13
)
The second is not valid because the second position has the same value 11 both in key and in value.
My attempt was this:
$result = array();
$array = array(10, 11, 12, 13, 14, 15);
$copy = array(10, 11, 12, 13, 14, 15);
foreach ($array as $a) {
$b = array_rand($copy, 1);
while (!in_array($copy[$b], $result)) {
if ($a != $copy[$b])
$result[$a] = $copy[$b];
else
$b = array_rand($copy, 1);
}
unset($copy[$b]);
}
It often works, but there’s a time when he doesn’t leave the while, then reaches the maximum execution time.
Perfect, everything worked out in the test. Thank you!
– Paulo Rodrigues