I have a PHP script as follows:
<?php
$a = [1 => 1, 2 => 2, 3 => 3];
for ($x=1; $x<10; $x++) {
$r = array_rand($a);
echo $a[$r] . '<br>';
}
?>
The output for this is random every time, but as an example it may be this:
2 1 3 3 2 3 1 3 2
What I'm trying to achieve is to make sure that each time a value is output it is different from the previous value. So in the example above I don't want 3 3 to occur.
I tried to come up with my own solution which involved storing the "current" output value in a variable called $current_value and making sure it's not what's going to be output next:
<?php
$a = [1 => 1, 2 => 2, 3 => 3];
$current_value = false;
for ($x=1; $x<10; $x++) {
if ($current_value) {
$r = array_rand($a);
while ($current_value !== $r) {
echo $a[$r] . '<br>';
$current_value = $a[$r];
}
} else {
$r = array_rand($a);
echo $a[$r] . '<br>';
$current_value = $a[$r];
}
}
?>
Although I don't get the same value appearing in sequence (at least from what I've tested) the loop only outputs a random number of figures which is usually less than $x<10. My guess here is that there's nothing to handle $current_value == $r so it simply outputs nothing?
Please could someone advise on how to achieve this? The expected output is 9 (or whatever the for loop counter is set to) integers with no overlap in the sequence, e.g.
2 1 3 1 2 3 1 3 2
Edit: The value which is output must always be 1, 2 or 3. This is why I was using $a as defined.