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?
$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]];
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>';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.