Question

I'm using PHP rand function to generate a number between 1 and 6 and doing it three times like this:

echo rand(1, 6);
echo "<br>";
echo rand(1, 6);
echo "<br>";
echo rand(1, 6);
echo "<br>";

Is there a way to prevent the same number from appearing in any of the 3 random numbers?

Was it helpful?

Solution

$random = range(1,6);
shuffle($random);
echo $random[0];
echo "<br>";
echo $random[1];
echo "<br>";
echo $random[2];

or

$input = range(1,6);
$random = array_rand($input);
echo $input[$random[0]];
echo "<br>";
echo $input[$random[1]];
echo "<br>";
echo $input[$random[2]];

OTHER TIPS

Try this code

<?php   

$out = array(); // We place generated values here
for ($i=0;$i<3;$i++ ) // 3 id the count of numbers
{
    $r = rand(1,6);
    while (in_array($r, $out)) { // if rand is already used then new rand
        $r = rand(1,6);
    }
    echo $r.'<br />';
    $out[] = $r;
}
 ?>
$random = rand(1,6);
$random2 = rand(1,6);
while($random2==$random){
    $random2 =rand(1,6);
}
$random3 = rand(1,6);
while($random3==$random||$random3==$random2){
    $random3=rand(1,6);
}
echo $random."<br>";
echo $random2."<br>";
echo $random3."<br>";

You use range(), array_shift() and shuffle() functions to get what you want

$arr = range(0, 6);
shuffle($arr);

echo array_shift($arr);
echo array_shift($arr);
echo array_shift($arr);
echo array_shift($arr);
$ar = range(1,6);
shuffle($ar);
echo implode('<br>', array_slice($ar,0,3)) . '<br>';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top