0

I have generated in an array 6 random numbers using the rand() function. I would like to ensure that none of these numbers are duplicates. I have written:

$lucky_numbers = array (rand (1,50), rand (1,50),rand (1,50),rand (1,50),rand (1,50),rand (1,50));
if ($lucky_numbers[0] == $lucky_numbers[1]) {
  print "same";
  $lucky_numbers[1]++;
}
if ($lucky_numbers[1] > 50) {
  $lucky_numbers[1] = $lucky_numbers[1]- 6;
}

and then checked each consecutive number with a similar code. But something doesn't work. Any ideas ? Thanks in advance.

pajaja
  • 2,164
  • 4
  • 25
  • 33
Robin
  • 37
  • 2

1 Answers1

1

Just use the shuffle function.

<?php
$numbers = range(1, 50);
shuffle($numbers);
for ($x=1;$x<=6;$x++){ 
  echo $numbers[$x] . "\n";
}
?>

See codepad example

Hugo Delsing
  • 13,803
  • 5
  • 45
  • 72
  • you might instead want to use `array_search` to save some memory as you arent requesting large amount of unique numbers this might be even faster as well. – Gal Sisso Jan 31 '15 at 21:44
  • `faster` and `save_memory` can only be true for large amounts of data. With 50 keys I couldn't get it slower unless I use `sleep`. – Hugo Delsing Jan 31 '15 at 21:53
  • Also I have no idea what you are searching for. – Hugo Delsing Jan 31 '15 at 21:54
  • True but wasting memory like this in large application eventually will end up being slower,you always need to think of ways to improve performance. $lucky_numbers = []; for($i=0;$i<6;$i++){ do $tmp_rand = rand(1, 50); while(array_search($tmp_rand,$lucky_numbers)); $lucky_numbers[] = $tmp_rand; } – Gal Sisso Feb 01 '15 at 09:49