0

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?

0

5 Answers 5

5
$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]];
Sign up to request clarification or add additional context in comments.

3 Comments

echo implode("\n", $random) . "\n";? ;P
If they want all of them, sure
You'd better use array_shift so you don't have to care of indexes.
1

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;
}
 ?>

Comments

0
$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>";

Comments

0

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);

Comments

0
$ar = range(1,6);
shuffle($ar);
echo implode('<br>', array_slice($ar,0,3)) . '<br>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.