Help!Generating random number without the generated numbers already ??

Discussion in 'PHP' started by jigen7, Sep 21, 2007.

  1. #1
    can anyone hep me me make a function that return random numbers but it will not generate another random number if he already pass the value for example it return 2, so after i call the function random again it will not return another 2 i want another numbers to be returned instead ?? can anyone help me here?

    function random($max){
    srand ((double) microtime( )*1000000);
    $random_number = rand(0,$max);
    return $random_number;
    }
     
    jigen7, Sep 21, 2007 IP
  2. krt

    krt Well-Known Member

    Messages:
    829
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    120
    #2
    I couldn't reproduce that issue using that code (on PHP 5.2)

    mt_rand provides better random number by the way:
    function random($max){
      return mt_rand(0,$max);
    }
    PHP:
    Up to you if you still want to use the wrapper, I don't bother with one.
     
    krt, Sep 21, 2007 IP
  3. jigen7

    jigen7 Peon

    Messages:
    42
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    nice thx but how can i get the function to return numbers that are not alraedy returned?
     
    jigen7, Sep 21, 2007 IP
  4. krt

    krt Well-Known Member

    Messages:
    829
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    120
    #4
    Oh, I thought you meant the subsequent numbers were all the same instead of "they should never be the same".

    function random($max) {
      static $numbers = array();
      do { $n = mt_rand(0, $max); }
      while (in_array($n, $numbers));
      return $numbers[] = $n;
    }
    PHP:
     
    krt, Sep 21, 2007 IP
  5. jigen7

    jigen7 Peon

    Messages:
    42
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    nice one thx very much really appreciate your help
     
    jigen7, Sep 21, 2007 IP