SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot
    Join Date
    Dec 1999
    Posts
    137
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Select numbers randomly

    Hi all,

    Im making this PHP script for a client and have this problem. I need to make a script that randomly grabs 50 numbers from 1 to 150 without duplicate values. So I thought about something like this
    PHP Code:
    header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    header ("Last-Modified: " gmdate("D, d M Y H:i:s") . " GMT"); 
    header ("Cache-Control: no-cache, must-revalidate");
    header ("Pragma: no-cache");
    function 
    random($sel=50,$de=150){
    $pregs=Array();
    for(
    $x=1;$x<=$sel;$x){
    $pregnum=rand(1,$de);
    while(!
    in_array($pregnum,$pregs)){
    $pregs[]=$pregnum;
    $x++;


    for(
    $x=0;$x<=count($pregs);$x++){
    echo 
    "$pregs[$x] ";
    }
    }
    random(); 
    The problem is that, although I receive randomly generated numbers, I always get the same number sequence (141 42 134 22 113...). Script can be found here. How can I solve this problem?. Thanks in advance.

  2. #2
    epsilon transition cupid's Avatar
    Join Date
    Aug 2001
    Location
    Kent, Ohio
    Posts
    367
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try running srand(mktime()); before you make the rand() call.

  3. #3
    SitePoint Zealot
    Join Date
    Dec 1999
    Posts
    137
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Works great! Thanks!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •