Reputation: 53
I am developing a very big application where i want to create very very unique random numbers which will never ever match the previous records.Here is my code
function random_number($maxlength = 17) {
$chary = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
$return_str = "";
for ( $x=0; $x<=$maxlength; $x++ ) {
$return_str .= $chary[rand(0, count($chary))];
}
return $return_str;
}
Now it works fine but some time it give me error
Notice: Undefined offset: 62 in test.php on line 8
Where line 8 is
$return_str .= $chary[rand(0, count($chary))];
Can anyone fix this for me?
Secondly is there any function in CI for random numbers?
Upvotes: 1
Views: 6412
Reputation: 34123
I am developing a very big application where i want to create very very unique random numbers which will never ever match the previous records
Then don't use any of these functions:
rand()
mt_rand()
lcg_value()
str_shuffle()
uniqid()
They're all weak. Instead, you want random_int()
. Otherwise, the accepted answer is... acceptable.
Upvotes: 0
Reputation: 401
Try uniqid it is standard php function and you dont need to invent your own bicycle. There is downsides in it but its other topic.
Upvotes: 0
Reputation: 16963
From the manual,
int rand ( int $min , int $max )
If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15).
So you have to change the range parameter in rand()
function, from rand(0, count($chary))
to rand(0, count($chary)-1)
function random_number($maxlength = 17) {
$chary = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
$return_str = "";
for ( $x=0; $x<=$maxlength; $x++ ) {
$return_str .= $chary[rand(0, count($chary)-1)];
}
return $return_str;
}
Upvotes: 1