2

I have problem with the rand function and i see each time i reload website repit in many cases de same number i put my script of example to continue :

for($i=0;$i<3;$i++)
{
$a=rand(0,2);
echo $a;
}

The result of this script in many cases can be this and right , (1,4,5) or in other cases with this problem (1,2,2) or (2,3,2) ( repit random number)

In many cases repit one number and this result repit one pic or one video and no show all differents results

Thank´s Regards

user2501504
  • 311
  • 3
  • 7
  • 15

2 Answers2

2

In your case, prepare an array that contains the numbers from 0 to 6 and shuffle it:

$a = range(0, 6);
shuffle($a);
foreach ($a as $x) { echo $x; }

Another option would be to store a list of already-generated values and using rejection sampling, that is, try again until you find a value that isn't already in the list. Which method to use (either shuffling a pre-made list and returning it or a sublist of it or rejection sampling) mostly depends on the range of allowed numbers and the number of items to return. If you have to generate 7 unique numbers from (0, 6), like in your case, however, shuffling is almost always the right choice. On the other hand, if you have to yield three unique numbers from (0, 1020) the tradeoff looks very different.

Joey
  • 344,408
  • 85
  • 689
  • 683
0

Another way is to store the last random value in a session and restart the loop if the number is equal:

for($i=0;$i<3;$i++)
{
    $a=rand(0,2);
    if(isset($_SESSION['lastRand']) && $a == $_SESSION['lastRand']) {
        $i = 0;
        continue;
    }
    $_SESSION['lastRand'] = $a;
    echo $a;
}
Remko
  • 968
  • 6
  • 19