+ Reply to Thread
Results 1 to 8 of 8

Thread: I need to generate a random number in PHP

  1. #1
    Programming Expert dirkfirst is on a distinguished road
    Join Date
    May 2006
    Posts
    354

    I need to generate a random number in PHP

    I am making a program and need a random number to select a feature. How do I generate a random number in PHP?
    DirkFirst

  2. #2
    Programmer RobSoftware is an unknown quantity at this point
    Join Date
    Nov 2005
    Posts
    143
    Easy:

    Code:
    <?php
    
    $min = 0;
    $max = 100;
    
    srand((double)microtime()*1000000);  
    echo rand($min,$max); 
    
    ?>
    replace $min and $max with whatever you like.

  3. #3
    Programmer RobSoftware is an unknown quantity at this point
    Join Date
    Nov 2005
    Posts
    143
    I forgot to mention, go here for more info:

    http://www.php.net/manual/function.rand.php

  4. #4
    The Crazy One TkTech will become famous soon enough TkTech's Avatar
    Join Date
    Jun 2006
    Location
    Canada
    Age
    18
    Posts
    1,549
    Blog Entries
    1
    RobSoftware:
    All new versions of php (4+) no longer require srand before rand, it does it automaticly when rand is called.

  5. #5
    Programming God NeedHelp is on a distinguished road
    Join Date
    May 2006
    Posts
    526
    So the new code would look like:

    Code:
    <?php

    $min 
    0;
    $max 100;

    echo 
    rand($min,$max); 

    ?>
    I Need Help

  6. #6
    The Crazy One TkTech will become famous soon enough TkTech's Avatar
    Join Date
    Jun 2006
    Location
    Canada
    Age
    18
    Posts
    1,549
    Blog Entries
    1
    bingo needhelp

  7. #7
    Programming Expert dirkfirst is on a distinguished road
    Join Date
    May 2006
    Posts
    354
    Thank you guys
    DirkFirst

  8. #8
    Kaabi
    Guest
    That second code looks much better than the first code. I once wrote a random name generator in C++ (I don't remember how to now, it was when I was trying to learn C++), and it was pretty cool, I only used it once.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

     

Similar Threads

  1. PHP 4 end of life announcement
    By Jordan in forum News
    Replies: 4
    Last Post: 08-30-2007, 09:55 AM
  2. Generating Random Numbers with PHP
    By Paradine in forum PHP Tutorials
    Replies: 4
    Last Post: 08-27-2007, 07:09 PM
  3. Floating Point random number generator
    By Paradine in forum PHP Tutorials
    Replies: 0
    Last Post: 08-26-2007, 02:09 PM

Bookmarks

Bookmarks

     
        Algorithms and Data Structures

        Java tutorials

        Algorithms Forum

Posting Permissions

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