简体   繁体   中英

Php not repeating random value

How can I get a not repeating random value, I tried this but did not work got an error:

    $randomdate = mt_rand(1, 52);
    $newdate = shuffle($randomdate);
    echo $newdate;

And got this error:

Warning: shuffle() expects parameter 1 to be array, integer given

TL;DR :

$nums = range(1, 52);
shuffle($nums);
while (sizeof($nums)) print array_pop($nums)."\n";

(Thanks to XicoXperto and Kevinrob.)

Full version:

I understand from your question update that you mean " I want a list of unique numbers, randomly ordered ".

For that you can use the (not particularly awesome-sauce) shuffle() (which you obviously know of!)

shuffle() only operates on arrays (thus your error message) - so we need to generate an array of integers from 1 to 52 inclusive:

$nums = array();                  // Declare empty array
for ($i = 1; $i <= 52; $i++) {    // From 1 to 52 inclusive
   $nums[] = $i;                  //   Populate unique numbers in array
}
shuffle($nums);                   // Shuffle array randomly

Now we can just start popping / shifting numbers off the array:

while (sizeof($nums) > 0) {
   print array_shift($nums) . "\n";
}

Optimised version (kudos to Kevinrob):

$nums = range(1, 52);             // Declare array of numbers 1..52
shuffle($nums);                   // Shuffle array randomly

Performance is doubled:

Loop:  0.48s (10,000)
Range: 0.26s (10,000)

Another optimisation provided regarding array_shift vs array_pop - the latter is less intensive - it'll give no less "randomness" (just works off the other end of the array) - thanks to XicoXperto!

array_shift: 2.20s (100,000)
array_pop:   1.40s (100,000)

Use array_rand() to random and pick N values (in this case, 10 times as you said), and range() to set limits, in your case, from 1 to 52.

<?php

    print_r( array_rand( range( 1, 52 ), 10 ) );

?>

Or, if you want to shuffle() results, then...

<?php

$numbers = array_rand( range( 1, 52 ), 10 ) ;
shuffle( $numbers );
print_r( $numbers );

?>

You have 2 ways to do this (that I can think atm)

1st way

$totalRandomNumbers = 4;
$randomValues = range(1, 52);
$result = array_rand($randomValues, $totalRandomNumbers);

variables:

  • $totalRandomNumbers is the total of random values that you want to get
  • $results the array variable that will contain the random values
  • $randomValues will be a array with all the possible values (1, 2, 3, 4, ..., 50, 51, 52)

logic: - range(1, 52) generate the array with all values from 1 to 52 - array_rand($randomValues, $totalRandomNumbers) will get randomly the amount of $totalRandomNumbers from the $randomValues list

2nd way REMOVED

it would take loads amount of processing and that means more time, so I took it

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM