I'm trying to create a function that will echo a new value between 1 and 6, but it can't be within + or - 1 of the last time the function was run. (i.e. If the last time it ran it got 4, I need a new value between 1 and 6 that's not 3, 4, or 5.)
As a php noob here's what I have so far:
$prev_val = 8;
function wordsize () {
global $prev_val;
$size_array = range(1,6);
do {
$new_val = $size_array[array_rand($size_array)];
} while($new_val>$prev_val-1 && $new_val<$prev_val+1);
echo "$new_val";
$prev_val = $new_val;
}
$size_array = array_diff(range(1,6), range($prev_val - 1, $prev_val + 1));
Which removes the need for a while
entirely.
You almost got it, you need to use >= and <= in your while loop:
while($new_val>=$prev_val-1 && $new_val<=$prev_val+1);
However, it might be better to get rid of the while loop entirely. See @wrikken's answer.