PHP equivalent of javascript Math.random()
You could use a function that returns the value:
PHP
function random() {
return (float)rand()/(float)getrandmax();
}
// Generates
// 0.85552537614063
// 0.23554185613575
// 0.025269325846126
// 0.016418958098086
JavaScript
var random = function () {
return Math.random();
};
// Generates
// 0.6855146484449506
// 0.910828611580655
// 0.46277225855737925
// 0.6367355801630765
@elclanrs solution is easier and doesn't need the cast in return.
Update
There's a good question about the difference between PHP mt_rand()
and rand()
here:
What's the disadvantage of mt_rand?
Javascript's Math.random gives a random number between 0 and 1. Zero is a correct output, but 1 should not be included. @thiagobraga's answer could give 1 as an output. My solution is this:
function random(){
return mt_rand() / (mt_getrandmax() + 1);
}
This will give a random number between 0 and 0.99999999953434.