Random numbers with rand() and one seed - php

I have to generate a large number of unique keys. One key should consist of 16 digits. I came up with the following code:
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
function generate_4_digits(){
$randval = rand(100, 9999);
if($randval < 1000){
$randval = '0'.$randval;
}
return (string)$randval;
}
function generate_cdkey(){
return generate_4_digits() . '-' . generate_4_digits() . '-' . generate_4_digits() . '-' . generate_4_digits();
}
srand(make_seed());
echo generate_cdkey();
The result was quite promising, 6114-0461-7825-1604.
Then I decided to generate 10 000 keys and see how many duplicates I get:
srand(make_seed());
$keys = array();
$duplicates = array();
for($i = 0; $i < 10000; $i++){
$new_key = generate_cdkey();
if(in_array($new_key, $keys)){
$duplicates[] = $new_key;
}
$keys[] = $new_key;
}
$keys_length = count($keys);
var_dump($duplicates);
echo '<pre>';
for($i = 0; $i < $keys_length; $i++){
echo $keys[$i] . "\n";
}
echo '</pre>';
On first run I got 1807 duplicates which was quite disappointing. But for my great surprise on each following run I get the same number of duplicates!? When I looked closely at the generated keys, I realized the last 1807 keys were exactly the same as the first ones. So I can generate 8193 without a single duplicate?! This is so close to 2^13?! Can we conclude rand() is suited to generate maz 2^13 unique numbers? But why?
I changed the code to use mt_rand() and I get no duplicates even when generating 50 000 keys.

This is probably more what you're looking for. openssl_random_pseudo_bytes ( int $length [, bool &$crypto_strong ] )

Throw some uniquid() in there.
http://www.php.net/manual/en/function.uniqid.php

This might be something to do with the behaviour of srand. When checking for duplicates you are only running srand once for all 10000 keys. Perhaps srand only produces enough for ~2^13 keys? What PHP version are you using? Since 4.2.0 srand isn't needed any more, but perhaps in if you call it anyway it stops doing it automatically for the rest of the script.

Related

Random generator returning endless duplicates

I am trying to create a random string which will be used as a short reference number. I have spent the last couple of days trying to get this to work but it seems to get to around 32766 records and then it continues with endless duplicates. I need at minimum 200,000 variations.
The code below is a very simple mockup to explain what happens. The code should be syntaxed according to 1a-x1y2z (example) which should give a lot more results than 32k
I have a feeling it may be related to memory but not sure. Any ideas?
<?php
function createReference() {
$num = rand(1, 9);
$alpha = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 1);
$char = '0123456789abcdefghijklmnopqrstuvwxyz';
$charLength = strlen($char);
$rand = '';
for ($i = 0; $i < 6; $i++) {
$rand .= $char[rand(0, $charLength - 1)];
}
return $num . $alpha . "-" . $rand;
}
$codes = [];
for ($i = 1; $i <= 200000; $i++) {
$code = createReference();
while (in_array($code, $codes) == true) {
echo 'Duplicate: ' . $code . '<br />';
$code = createReference();
}
$codes[] = $code;
echo $i . ": " . $code . "<br />";
}
exit;
?>
UPDATE
So I am beginning to wonder if this is not something with our WAMP setup (Bitnami) as our local machine gets to exactly 1024 records before it starts duplicating. By removing 1 character from the string above (instead of 6 in the for loop I make it 5) it gets to exactly 32768 records.
I uploaded the script to our centos server and had no duplicates.
What in our enviroment could cause such a behaviour?
The code looks overly complex to me. Let's assume for the moment you really want to create n unique strings each based on a single random value (rand/mt_rand/something between INT_MIN,INT_MAX).
You can start by decoupling the generation of the random values from the encoding (there seems to be nothing in the code that makes a string dependant on any previous state - excpt for the uniqueness). Comparing integers is quite a bit faster than comparing arbitrary strings.
mt_rand() returns anything between INT_MIN and INT_MAX, using 32bit integers (could be 64bit as well, depends on how php has been compiled) that gives ~232 elements. You want to pick 200k, let's make it 400k, that's ~ a 1/10000 of the value range. It's therefore reasonable to assume everything goes well with the uniqueness...and then check at a later time. and add more values if a collision occured. Again much faster than checking in_array in each iteration of the loop.
Once you have enough values, you can encode/convert them to a format you wish. I don't know whether the <digit><character>-<something> format is mandatory but assume it is not -> base_convert()
<?php
function unqiueRandomValues($n) {
$values = array();
while( count($values) < $n ) {
for($i=count($values);$i<$n; $i++) {
$values[] = mt_rand();
}
$values = array_unique($values);
}
return $values;
}
function createReferences($n) {
return array_map(
function($e) {
return base_convert($e, 10, 36);
},
unqiueRandomValues($n)
);
}
$start = microtime(true);
$references = createReferences(400000);
$end = microtime(true);
echo count($references), ' ', count(array_unique($references)), ' ', $end-$start, ' ', $references[0];
prints e.g. 400000 400000 3.3981630802155 f3plox on my i7-4770. (The $end-$start part is constantly between 3.2 and 3.4)
Using base_convert() there can be strings like li10, which can be quite annoying to decipher if you have to manually type the string.

Why does this random string generator perform so poorly?

I found this bit of PHP code for generating random strings (alphabetical, alphanumeric, numeric, and hexadecimal).
<?php
function random($length = 8, $seeds = 'alpha') {
// Possible seeds
$seedings['alpha'] = 'abcdefghijklmnopqrstuvwqyz';
$seedings['numeric'] = '0123456789';
$seedings['alphanum'] = 'abcdefghijklmnopqrstuvwqyz0123456789';
$seedings['hexidec'] = '0123456789abcdef';
// Choose seed
if (isset($seedings[$seeds])) {
$seeds = $seedings[$seeds];
}
// Seed generator
list($usec, $sec) = explode(' ', microtime());
$seed = (float) $sec + ((float) $usec * 100000);
mt_srand($seed);
// Generate
$str = '';
$seeds_count = strlen($seeds);
for ($i = 0; $length > $i; $i++) {
$str .= $seeds{mt_rand(0, $seeds_count - 1)};
}
return $str;
}
?>
If I run this function with the default arguments (so it is generating 8 character strings, alphabetical only) and generate 1,000,000 strings, I'd think my collision rate would be low:
26^8 = 208,827,064,576
1,000,000 / 208,827,064,576 ~= 0.0004%
In actuality, when I run that on my machine, I get a 90% collision rate! Only 10% of my generated strings are unique.
Actually, it is suspiciously close to 10%. Generating multiple sets of 1,000,000 random strings, I find that each set generates...
100,032 unique strings
100,035 unique strings
100,032 unique strings
100,028 unique strings
100,030 unique strings
you get the idea...
So what gives? Obviously it has to do with how I'm seeding mt_srand, or how php implements mt_rand, or something else.
So...
Why doesn't this code generate useful random strings?
And what would be a better approach?
Don't set the seed unless you know what you're doing, from the manual:
Note: There is no need to seed the random number generator with
srand() or mt_srand() as this is done automatically.
The following code gets me almost a set of 100% unique strings
<?php
function random($length = 8, $charset = 'alpha'){
$list = [
'alpha' => 'abcdefghijklmnopqrstuvwqyz',
'numeric' => '0123456789',
'alphanum' => 'abcdefghijklmnopqrstuvwqyz0123456789',
'hexidec' => '0123456789abcdef'
];
if(!isset($list[$charset])){
trigger_error("Invalid charset '$charset', allowed sets: '".implode(', ', array_keys($list))."'", E_USER_NOTICE);
$charset = 'alpha';
}
$str = '';
$max = strlen($list[$charset]) - 1;
for ($i = 0; $length > $i; $i++) {
$str .= $list[$charset][mt_rand(0, $max)];
}
return $str;
}
$loop = 1000000;
for($i=0;$i<$loop;$i++){
$arr[random()] = true;
}
echo $loop - count($arr), " dupes found in list.";
?>

One-line PHP random string generator?

I am looking for the shortest way to generate random/unique strings and for that I was using the following two:
$cClass = sha1(time());
or
$cClass = md5(time());
However, I need the string to begin with a letter, I was looking at base64 encoding but that adds == at the end and then I would need to get rid of that.
What would be the best way to achieve this with one line of code?
Update:
PRNDL came up with a good suggestions which I ended up using it but a bit modified
echo substr(str_shuffle(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ),0, 1) . substr(str_shuffle(aBcEeFgHiJkLmNoPqRstUvWxYz0123456789),0, 31)
Would yield 32 characters mimicking the md5 hash but it would always product the first char an alphabet letter, like so;
However, Uours really improved upon and his answer;
substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1).substr(md5(time()),1);
is shorter and sweeter
The other suggestion by Anonymous2011 was very awesome but the first character for some reason would always either M, N, Y, Z so didn't fit my purposes but would have been the chosen answer, by the way does anyone know why it would always yield those particular letters?
Here is the preview of my modified version
echo rtrim(base64_encode(md5(microtime())),"=");
Rather than shuffling the alphabet string , it is quicker to get a single random char .
Get a single random char from the string and then append the md5( time( ) ) to it . Before appending md5( time( ) ) remove one char from it so as to keep the resulting string length to 32 chars :
substr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", mt_rand(0, 51), 1).substr(md5(time()), 1);
Lowercase version :
substr("abcdefghijklmnopqrstuvwxyz", mt_rand(0, 25), 1).substr(md5(time()), 1);
Or even shorter and a tiny bit faster lowercase version :
chr(mt_rand(97, 122)).substr(md5(time()), 1);
/* or */
chr(mt_rand(ord('a'), ord('z'))).substr(md5(time()), 1);
A note to anyone trying to generate many random strings within a second: Since time( ) returns time in seconds , md5( time( ) ) will be same throughout a given second-of-time due to which if many random strings were generated within a second-of-time, those probably could end up having some duplicates .
I have tested using below code . This tests lower case version :
$num_of_tests = 100000;
$correct = $incorrect = 0;
for( $i = 0; $i < $num_of_tests; $i++ )
{
$rand_str = substr( "abcdefghijklmnopqrstuvwxyz" ,mt_rand( 0 ,25 ) ,1 ) .substr( md5( time( ) ) ,1 );
$first_char_of_rand_str = substr( $rand_str ,0 ,1 );
if( ord( $first_char_of_rand_str ) < ord( 'a' ) or ord( $first_char_of_rand_str ) > ord( 'z' ) )
{
$incorrect++;
echo $rand_str ,'<br>';
}
else
{
$correct++;
}
}
echo 'Correct: ' ,$correct ,' . Incorrect: ' ,$incorrect ,' . Total: ' ,( $correct + $incorrect );
I had found something like this:
$length = 10;
$randomString = substr(str_shuffle(md5(time())),0,$length);
echo $randomString;
If you need it to start with a letter, you could do this. It's messy... but it's one line.
$randomString = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1) . substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10);
echo $randomString;
I decided this question needs a better answer. Like code golf! This also uses a better random byte generator.
preg_replace("/[\/=+]/", "", base64_encode(openssl_random_pseudo_bytes(8)));
Increase the number of bytes for a longer password, obviously.
Creates a 200 char long hexdec string:
$string = bin2hex(openssl_random_pseudo_bytes(100));
maaarghk's answer is better though.
base_convert(microtime(true), 10, 36);
You can try this:
function KeyGenerator($uid) {
$tmp = '';
for($z=0;$z<5;$z++) {
$tmp .= chr(rand(97,122)) . rand(0,100);
}
$tmp .= $uid;
return $tmp;
}
I have generated this code for you. Simple, short and (resonably) elegant.
This uses the base64 as you mentioned, if length is not important to you - However it removes the "==" using str_replace.
<?php
echo str_ireplace("==", "", base64_encode(time()));
?>
I use this function
usage:
echo randomString(20, TRUE, TRUE, FALSE);
/**
* Generate Random String
* #param Int Length of string(50)
* #param Bool Upper Case(True,False)
* #param Bool Numbers(True,False)
* #param Bool Special Chars(True,False)
* #return String Random String
*/
function randomString($length, $uc, $n, $sc) {
$rstr='';
$source = 'abcdefghijklmnopqrstuvwxyz';
if ($uc)
$source .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if ($n)
$source .= '1234567890';
if ($sc)
$source .= '|##~$%()=^*+[]{}-_';
if ($length > 0) {
$rstr = "";
$length1= $length-1;
$input=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')
$rand = array_rand($input, 1)
$source = str_split($source, 1);
for ($i = 1; $i <= $length1; $i++) {
$num = mt_rand(1, count($source));
$rstr1 .= $source[$num - 1];
$rstr = "{$rand}{$rstr1}";
}
}
return $rstr;
}
I'm using this one to generate dozens of unique strings in a single go, without repeating them, based on other good examples above:
$string = chr(mt_rand(97, 122))
. substr(md5(str_shuffle(time() . rand(0, 999999))), 1);
This way, I was able to generate 1.000.000 unique strings in ~5 seconds. It's not THAT fast, I know, but as I just need a handful of them, I'm ok with it. By the way, generating 10 strings took less than 0.0001 ms.
JavaScript Solution:
function randomString(pIntLenght) {
var strChars = “0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz”;
var strRandomstring = ”;
for (var intCounterForLoop=0; intCounterForLoop < pIntLenght; intCounterForLoop++) {
var rnum = Math.floor(Math.random() * strChars.length);
strRandomstring += strChars.substring(rnum,rnum+1);
}
return strRandomstring;
}
alert(randomString(20));
Reference URL : Generate random string using JavaScript
PHP Solution:
function getRandomString($pIntLength = 30) {
$strAlphaNumericString = ’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;
$strReturnString = ”;
for ($intCounter = 0; $intCounter < $pIntLength; $intCounter++) {
$strReturnString .= $strAlphaNumericString[rand(0, strlen($strAlphaNumericString) - 1)];
}
return $strReturnString;
}
echo getRandomString(20);
Reference URL : Generate random String using PHP
This function returns random lowercase string:
function randomstring($len=10){
$randstr='';
for($iii=1; $iii<=$len; $iii++){$randstr.=chr(rand(97,122));};
return($randstr);
};
I find that base64 encoding is useful for creating random strings, and use this line:
base64_encode(openssl_random_pseudo_bytes(9));
It gives me a random string of 12 positions, with the additional benefit that the randomness is "cryptographically strong".
to generate strings consists of random characters, you can use this function
public function generate_random_name_for_file($length=50){
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
It really depends on your requirements.
I needed strings to be unique between test runs, but not many other restrictions.
I also needed my string to start with a character, and this was good enough for my purpose.
$mystring = "/a" . microtime(true);
Example output:
a1511953584.0997
How to match the OPs original request in an awful way (expanded for readability):
// [0-9] ASCII DEC 48-57
// [A-Z] ASCII DEC 65-90
// [a-z] ASCII DEC 97-122
// Generate: [A-Za-z][0-9A-Za-z]
$r = implode("", array_merge(array_map(function($a)
{
$a = [rand(65, 90), rand(97, 122)];
return chr($a[array_rand($a)]);
}, array_fill(0, 1, '.')),
array_map(function($a)
{
$a = [rand(48, 57), rand(65, 90), rand(97, 122)];
return chr($a[array_rand($a)]);
}, array_fill(0, 7, '.'))));
One the last array_fill() would would change the '7' to your length - 1.
For one that does all alpha-nurmeric (And still slow):
// [0-9A-Za-z]
$x = implode("", array_map(function($a)
{
$a = [rand(48, 57), rand(65, 90), rand(97, 122)];
return chr($a[array_rand($a)]);
}, array_fill(0, 8, '.')));
The following one-liner meets the requirements in your question: notably, it begins with a letter.
substr("abcdefghijklmnop",random_int(0, 16),1) . bin2hex(random_bytes(15))
If you didn't care whether the string begins with a letter, you could just use:
bin2hex(random_bytes(16))
Note that here we use random_bytes and random_int, which were introduced in PHP 7 and use cryptographic random generators, something that is important if you want unique strings to be hard to guess. Many other solutions, including those involving time(), microtime(), uniqid(), rand(), mt_rand(), str_shuffle(), array_rand(), and shuffle(), are much more predictable and are unsuitable if the random string will serve as a password, a bearer credential, a nonce, a session identifier, a "verification code" or "confirmation code", or another secret value.
I also list other things to keep in mind when generating unique identifiers, especially random ones.
True one liner random string options:
implode('', array_rand(array_flip(str_split(str_shuffle('abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'))), 21));
md5(microtime() . implode('', array_rand(array_flip(str_split(str_shuffle('abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'))), 21)));
sha1(microtime() . implode('', array_rand(array_flip(str_split(str_shuffle('abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'))), 21)));

php random x digit number

I need to create a random number with x amount of digits.
So lets say x is 5, I need a number to be eg. 35562
If x is 3, then it would throw back something like; 463
Could someone show me how this is done?
You can use rand() together with pow() to make this happen:
$digits = 3;
echo rand(pow(10, $digits-1), pow(10, $digits)-1);
This will output a number between 100 and 999. This because 10^2 = 100 and 10^3 = 1000 and then you need to subtract it with one to get it in the desired range.
If 005 also is a valid example you'd use the following code to pad it with leading zeros:
$digits = 3;
echo str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);
I usually just use RAND() http://php.net/manual/en/function.rand.php
e.g.
rand ( 10000 , 99999 );
for your 5 digit random number
Here is a simple solution without any loops or any hassle which will
allow you to create random string with characters, numbers or even with special symbols.
$randomNum = substr(str_shuffle("0123456789"), 0, $x);
where $x can be number of digits
Eg.
substr(str_shuffle("0123456789"), 0, 5);
Results after a couple of executions
98450
79324
23017
04317
26479
You can use the same code to generate random string also, like this
$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyzABCDEFGHIJKLMNOPQRSTVWXYZ"), 0, $x);
Results with $x = 11
FgHmqpTR3Ox
O9BsNgcPJDb
1v8Aw5b6H7f
haH40dmAxZf
0EpvHL5lTKr
You can use rand($min, $max) for that exact purpose.
In order to limit the values to values with x digits you can use the following:
$x = 3; // Amount of digits
$min = pow(10,$x);
$max = pow(10,$x+1)-1);
$value = rand($min, $max);
Treat your number as a list of digits and just append a random digit each time:
function n_digit_random($digits) {
$temp = "";
for ($i = 0; $i < $digits; $i++) {
$temp .= rand(0, 9);
}
return (int)$temp;
}
Or a purely numerical solution:
function n_digit_random($digits)
return rand(pow(10, $digits - 1) - 1, pow(10, $digits) - 1);
}
the simplest way i can think of is using rand function with str_pad
<?php
echo str_pad(rand(0,999), 5, "0", STR_PAD_LEFT);
?>
In above example , it will generate random number in range 0 to 999.
And having 5 digits.
function random_numbers($digits) {
$min = pow(10, $digits - 1);
$max = pow(10, $digits) - 1;
return mt_rand($min, $max);
}
Tested here.
rand(1000, 9999); works more faster than x4 times rand(0,9);
benchmark:
rand(1000, 9999) : 0.147 sec.
rand(0,9)x4 times : 0.547 sec.
both functions was running in 100000 iterations to make results more explicit
Well you can use as simple php function mt_rand(2000,9000) which can generate a 4 digit random number
mt_rand(2000,9000)
You can generate any x-digit random number with mt_rand() function.
mt_rand() is faster than rand().
Syntax : mt_rand() or mt_rand($min , $max).
Example : <?php echo mt_rand(); ?>
read more
do it with a loop:
function randomWithLength($length){
$number = '';
for ($i = 0; $i < $length; $i++){
$number .= rand(0,9);
}
return (int)$number;
}
rand or mt_rand will do...
usage:
rand(min, max);
mt_rand(min, max);
function random_number($size = 5)
{
$random_number='';
$count=0;
while ($count < $size )
{
$random_digit = mt_rand(0, 9);
$random_number .= $random_digit;
$count++;
}
return $random_number;
}
Following is simple method to generate specific length verification code. Length can be specified, by default, it generates 4 digit code.
function get_sms_token($length = 4) {
return rand(
((int) str_pad(1, $length, 0, STR_PAD_RIGHT)),
((int) str_pad(9, $length, 9, STR_PAD_RIGHT))
);
}
echo get_sms_token(6);
this simple script will do
$x = 4;//want number of digits for the random number
$sum = 0;
for($i=0;$i<$x;$i++)
{
$sum = $sum + rand(0,9)*pow(10,$i);
}
echo $sum;
This is another simple solution to generate random number of N digits:
$number_of_digits = 10;
echo substr(number_format(time() * mt_rand(),0,'',''),0,$number_of_digits);
Check it here: http://codepad.org/pyVvNiof
function rand_number_available($already_mem_array,$boundary_min,$boundary_max,$digits_num)
{
$already_mem_array_dim = count($already_mem_array); // dimension of array, that contain occupied elements
// --- creating Boundaries and possible Errors
if( empty($digits_num) ){
$boundary_dim = $boundary_max - $boundary_min;
if($boundary_dim <= 0){
$error = -1; // Error that might happen. Difference between $boundary_max and $boundary_min must be positive
}else{
$error = -2; // Error that might happen. All numbers between, $boundary_min and $boundary_max , are occupied, by $already_mem_array
}
}else{
if($digits_num < 0){ // Error. If exist, $digits_num must be, 1,2,3 or higher
$error = -3;
}elseif($digits_num == 1){ // if 'one-figure' number
$error = -4; // Error that might happen. All 'one-figure' numbers are occupied, by $already_mem_array
$boundary_min = 0;
$boundary_max = 9;
$boundary_dim = $boundary_max-$boundary_min;
}elseif($digits_num == 2){ // if 'two-figure' number
$error = -5; // Error that might happen. All 'two-figure' numbers are occupied, by $already_mem_array
$boundary_min = 10;
$boundary_max = 99;
$boundary_dim = $boundary_max-$boundary_min;
}elseif($digits_num>2){ // if 'X-figure' number. X>2
$error = -6; // Error that might happen. All 'X-figure' numbers are occupied, by $already_mem_array. Unlikely to happen
$boundary_min = pow(10, $digits_num-1); // stepenovanje - graduation
$boundary_max = pow(10, $digits_num)-1;
$boundary_dim = $boundary_max-$boundary_min;
}
}
// -------------------------------------------------------------------
// --- creating response ---------------------------------------------
if( ($already_mem_array_dim <= $boundary_dim) && $boundary_dim>0 ){ // go here only if, there are AVAILABLE numbers to extract, and [difference] $boundary_dim , is positive
do{
$num = rand($boundary_min,$boundary_max);
}while( in_array($num, $already_mem_array) );
$result = $num;
}else{
$result = $error; // Limit that happened
}
return $result;
// -------------------------------------------------------------------
}
This function works perfectly with no repeats and desired number of digits.
$digits = '';
function randomDigits($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0; $i < $length; $i++){
global $digits;
$digits .= $numbers[$i];
}
return $digits;
}
You can call the function and pass the number of digits for example:
randomDigits(4);
sample results:
4957 8710 6730 6082 2987 2041 6721
Original script got from this gist
Please not that rand() does not generate a cryptographically secure value according to the docs:
http://php.net/manual/en/function.rand.php
This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.
Instead it is better to use random_int(), available on PHP 7 (See: http://php.net/manual/en/function.random-int.php).
So to extend #Marcus's answer, you should use:
function generateSecureRandomNumber($digits): int {
return random_int(pow(10, $digits - 1), pow(10, $digits) - 1);
}
function generateSecureRandomNumberWithPadding($digits): string {
$randomNumber = random_int(0, pow(10, $digits) - 1);
return str_pad($randomNumber, $digits, '0', STR_PAD_LEFT);
}
Note that using rand() is fine if you don't need a secure random number.
The following code generates a 4 digits random number:
echo sprintf( "%04d", rand(0,9999));
you people really likes to complicate things :)
the real problem is that the OP wants to, probably, add that to the end of some really big number. if not, there is no need I can think of for that to be required. as left zeros in any number is just, well, left zeroes.
so, just append the larger portion of that number as a math sum, not string.
e.g.
$x = "102384129" . complex_3_digit_random_string();
simply becomes
$x = 102384129000 + rand(0, 999);
done.

php array_intersect() efficiency

consider the below script. two arrays with only three values.when i compare these two arrays using array_intersect(). the result is fast.
<?php
$arrayOne = array('3', '4', '5');
$arrayTwo = array('4', '5', '6');
$intersect = array_intersect($arrayOne, $arrayTwo);
print_r($intersect );
?>
my question is what is the efficiency of the array_intersect(). whether if we compare two arrays both having 1000 values each. would produce better result..... r we need to use some hash function to deal with finding common values quickly which will be effective???.. i need ur suggestion for this...
i am doing an application.if an person comes and login using facebook login.then the application will get his friends list and find whether any friends as commented in my app before and show it to him. roughly a friends may have 200 to300 friends in facebook and db has more than 1000 records. i need to find that efficiently how can i do that.......
Intersection can be implemented by constructing a set of the searched values in the second array, and looking up in a set can be made so fast that it takes essentially constant time on average. Therefore, the runtime of the whole algorithm can be in O(n).
Alternatively, one can sort the second array (in O(n log n)). Since looking up in a sorted array has a runtime in O(log n), the whole algorithm should then have a runtime in O(n log n).
According to a (short, unscientific) test I just ran, this seems to be the case for php's array_intersect:
Here's the code I used to test it. As you can see, for an input size as small as 1000, you don't need to worry.
array_intersect sorts the arrays before comparing their values in parallel (see the use of zend_qsort in the source file array.c). This alone takes O(n·log n) for each array. Then the actual intersection does only take linear time.
Depending on the values in your arrays, you could implement this intersection in linear time without the sorting, for example:
$index = array_flip($arrayOne);
foreach ($arrayTwo as $value) {
if (isset($index[$value])) unset($index[$value]);
}
foreach ($index as $value => $key) {
unset($arrayOne[$key]);
}
var_dump($arrayOne);
The fastest solution I found:
function arrayIntersect($arrayOne, $arrayTwo) {
$index = array_flip($arrayOne);
$second = array_flip($arrayTwo);
$x = array_intersect_key($index, $second);
return array_flip($x);
}
Tests I have made looks like below:
function intersect($arrayOne, $arrayTwo)
{
$index = array_flip($arrayOne);
foreach ($arrayTwo as $value) {
if (isset($index[$value])) unset($index[$value]);
}
foreach ($index as $value => $key) {
unset($arrayOne[$key]);
}
return $arrayOne;
}
function intersect2($arrayOne, $arrayTwo)
{
$index = array_flip($arrayOne);
$second = array_flip($arrayTwo);
$x = array_intersect_key($index, $second);
return array_flip($x);
}
for($i =0; $i < 1000000; $i++) {
$one[] = rand(0,1000000);
$two[] = rand(0,100000);
$two[] = rand(0,10000);
}
$one = array_unique($one);
$two = array_unique($two);
$time_start = microtime(true);
$res = intersect($one, $two);
$time = microtime(true) - $time_start;
echo "Sort time $time seconds 'intersect' \n";
$time_start = microtime(true);
$res2 = array_intersect($one, $two);
$time = microtime(true) - $time_start;
echo "Sort time $time seconds 'array_intersect' \n";
$time_start = microtime(true);
$res3 = intersect2($one, $two);
$time = microtime(true) - $time_start;
echo "Sort time $time seconds 'intersect2' \n";
Results from php 5.6 :
Sort time 0.77021193504333 seconds 'intersect'
Sort time 6.9765028953552 seconds 'array_intersect'
Sort time 0.4631941318512 seconds 'intersect2'
From what you state above, I would recommend you to implement a caching mechanism. That way you would of load the DB and speed up your application. I would also recommend you to profile the speed of array_intersect with increasing amount of data to see how performance scale. You could do this by simply wrapping the call in calls for the system time and calculate the difference. But I would recommend you to use a real profiler to get good data.
I implementing this simple code of comparing array_intersect and array_intersect_key,
$array = array();
for( $i=0; $i<130000; $i++)
$array[$i] = $i;
for( $i=200000; $i<230000; $i++)
$array[$i] = $i;
for( $i=300000; $i<340000; $i++)
$array[$i] = $i;
$array2 = array();
for( $i=100000; $i<110000; $i++)
$array2[$i] = $i;
for( $i=90000; $i<100000; $i++)
$array2[$i] = $i;
for( $i=110000; $i<290000; $i++)
$array2[$i] = $i;
echo 'Intersect to arrays -> array1[' . count($array) . '] : array2[' . count($array2) . '] ' . '<br>';
echo date('Y-m-d H:i:s') . '<br>';
$time = time();
$array_r2 = array_intersect_key($array,$array2);
echo 'Intercept key: ' . (time()-$time) . ' segs<br>';
$time = time();
$array_r = array_intersect($array,$array2);
echo 'Intercept: ' . (time()-$time) . ' segs<br>';
the result....
Intersect to arrays -> array1[200000] : array2[200000]
2014-10-30 08:52:52
Intercept key: 0 segs
Intercept: 4 segs
In this comparing of the efficency between array_intersect and array_intersect_key, we can see the interception with keys it is much faster.

Categories