phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


PHP - Number: Generating Random Numbers

Tag: number, random   Category: PHP Basic
post: 16 Mar 2008 read: 48


PHP Number Tips - Part 18: If you want generate one or more random numbers, you can use PHP's rand( ) function:

<?php
//generate a random number
//result: 18785 (example)
echo rand();

//generate a random number between 0 and 100
//result: 4 (example)
echo rand(0, 100);
?>

Generating a random number in PHP is as simple as calling the rand( ) function. The getrandmax( ) function is a good choice in here where it returns the maximum value that rand( ) could possibly generate on your system. Here's an illustration:


<?php
// generate a random floating-point number
// result: 0.721182897427 (example)
echo rand()/getrandmax();
?>

If you need more than one random number, use rand( ) in combination with a loop and array such as:


<?php
//generate a series of 10 random numbers between 0 and 100
//result: "12 95 88 87 61 49 61 4 99 75" (example)
for ($x=0; $x<10; $x++) {
  echo rand(0, 100) . " ";
}
?>



| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


615
posting