Jump to content

How do I generate 4 different random numbers?


eugeniu

Recommended Posts

I'd do:

<?php
$i = 0;
while ($i < 4)
{
echo rand(0,100) . "<br />";
$i++;
}
?>

or:

$rand = array(rand(0,100),rand(0,100),rand(0,100),rand(0,100));
foreach ($rand as $val)
{
echo $val . "<br />";
}

or:

$rand1 = rand(0,100);
$rand2 = rand(0,100);
$rand3 = rand(0,100);
$rand4 = rand(0,100);
echo $rand1 ." ". $rand2 ." ". $rand3 ." ". $rand4;

 

Here's one way:

<?php
$ary = range(1,100);
shuffle($ary);
$nums = array_slice($ary,0,4);
echo '<pre>' . print_r($nums,true) . '</pre>';
?>

 

papaface: There's no guarantee that you will get 4 different numbers.

 

Ken

Here's one way:

<?php
$ary = range(1,100);
shuffle($ary);
$nums = array_slice($ary,0,4);
echo '<pre>' . print_r($nums,true) . '</pre>';
?>

 

papaface: There's no guarantee that you will get 4 different numbers.

 

Ken

 

Oo, thanks. Is there any way I can make each generated number a separate variable with that?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.