Generating Random Numbers in PHP
Published 2 years, 5 months ago in Basics and PHPTo create random numbers in PHP, you can use the rand() function call, which takes either zero or, optionally, two parameters determining the minimum and maximum random numbers (inclusive) that you'd like. If you don't specify a maximum then it will default to a value, RAND_MAX, set in the PHP configuration. The function returns an integer, generated "randomly." (Computers can't generate real random numbers, but this tries and is suitable for most purposes.)
You can get the value of RAND_MAX with the function getrandmax(). Then if you desire a random number larger than that, you have to specify the min and max bounds as parameters, eg rand(0, 100000) will return a random number between 0 and 100000 inclusive - so both 0 and 100000 can be returned.
For example:
-
<?php
-
// random number between 0 and RAND_MAX:
-
// random number between 37 and 50:
-
// find out the value of RAND_MAX:
-
// get a larger random number by specifying min and max:
-
?>
The output shown in the comments above is as an example. Since it is generating random numbers, the numbers generated are very likely to be be different every time.
If you have a website, consider joining the Money4Banners advertising network. They will pay you £10 + £5 each month for displaying a small advert on three of your pages, regardless of traffic. American webmasters are welcome, and since £10 == $20, you make more!
Search
Categories
- ASP (3)
- ASP Basics (3)
- Blogs (2)
- C# (1)
- deals (1)
- Firefox (1)
- Flash (1)
- Google (6)
- Hacks (4)
- Java (1)
- PHP (12)
- Basics (8)
- Files (1)
- Image Handling (3)
- Puzzles (1)
- Ruby (1)
- Tips (10)
- Web Hosting (3)
- Web Hosting Articles (1)
- Web Hosting News (2)
- Windows (6)
- Wordpress (2)
Related Entries
- PHP
- Random Colors in Flash
- How to use PHP in pages with a .html extension (or any other)
- Rotating Images with PHP
- Generate a Month Calendar In PHP
- Finding Items in an Array with PHP
- The Difference Between require() and include()
- Find a visitor's IP Address with PHP
- How to Find the Current URL with PHP
- How to use the query string in PHP
No Responses to “Generating Random Numbers in PHP”
Please Wait
Leave a Reply
You must log in to post a comment.