Jump to content

I need to generate a random number in PHP

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
7 replies to this topic

#1
dirkfirst

dirkfirst

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 354 posts
I am making a program and need a random number to select a feature. How do I generate a random number in PHP?

#2
RobSoftware

RobSoftware

    Programmer

  • Members
  • PipPipPipPip
  • 143 posts
Easy:


<?php


$min = 0;

$max = 100;


srand((double)microtime()*1000000);  

echo rand($min,$max); 


?>


replace $min and $max with whatever you like.

#3
RobSoftware

RobSoftware

    Programmer

  • Members
  • PipPipPipPip
  • 143 posts
I forgot to mention, go here for more info:

http://www.php.net/m...nction.rand.php

#4
TkTech

TkTech

    The Crazy One

  • Moderators
  • 1,396 posts
RobSoftware:
All new versions of php (4+) no longer require srand before rand, it does it automaticly when rand is called.

#5
Guest_NeedHelp_*

Guest_NeedHelp_*
  • Guests
So the new code would look like:


<?php


$min = 0;

$max = 100;


echo rand($min,$max); 


?>



#6
TkTech

TkTech

    The Crazy One

  • Moderators
  • 1,396 posts
bingo needhelp

#7
dirkfirst

dirkfirst

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 354 posts
Thank you guys

#8
Guest_Kaabi_*

Guest_Kaabi_*
  • Guests
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.