0

I want to change starting number by +1/-1 value.

Example:

$startNumber = 1;

Echo $startNumber randomly, if number is 1 echo random 0 or 2, if number is 2 echo random 1 or 3.

I hope I explained well, is it possible to do this?

NickCaves
  • 61
  • 1
  • 9
  • 1
    Possible duplicate of [PHP generate a random minus or plus percentage of a given value](https://stackoverflow.com/questions/17840009/php-generate-a-random-minus-or-plus-percentage-of-a-given-value) – splash58 Feb 20 '18 at 21:20

2 Answers2

0

Yes, it is possible.

$steps = 0;
$number = 1;
while ($steps < 100) {
    if (rand(0,1) === 0) {
        $number -= 1;
    } else {
        $number += 1;
    }
    $steps += 1;
    echo "<p>After step $steps, number is $number";
}
BareNakedCoder
  • 3,257
  • 2
  • 13
  • 16
0

There's many possible ways of doing so, for example:

function randomChange($myValue){
    $random = rand(0,1);
    if($random > 0)
        return $myValue + 1;

    return $myValue - 1;
}

$myValue = 1;
$myValue = randomChange($myValue);

echo $myValue;

Then itrerate it, or make it method if OOP. Hope it helps. Regards.

Bartek M
  • 1
  • 1