Jon Don
Jon Don

Reputation: 81

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

Upvotes: 2

Views: 1040

Answers (3)

BornKillaz
BornKillaz

Reputation: 602

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

?>

Upvotes: 2

wally
wally

Reputation: 3592

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)

Upvotes: 2

mloureiro
mloureiro

Reputation: 949

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

Upvotes: 0

Related Questions