This code creates a new random number each second.
srand(floor(time() / (1)));
echo rand(0,5);
How can it echo random numbers (0-5) uniquely, and then cycle?
For example, I'd love to get a sequence like this:
1,5,4,3,2,1,4,5,3,2,5,4,1,2,3...
Rather than this:
2,2,1,4,3,4,5,5,5,5,5,1,2,3,4...
(Just to clarify, the second gap is important, and you're to assume there's been a one second delay between each page load. Each page load results in a random number)
do you want to get rid of sequences like "2,2" and "5,5,5,5"? it's possible only if you store previous number somewhere, e.g. in $_SESSION superglobal var:
session_start();
$ran_num = rand(0, 5);
while ($ran_num == $_SESSION['ran_num']) {
$ran_num = rand(0, 5);
}
$_SESSION['ran_num'] = $ran_num;
echo $ran_num;
Related
So, I,been trying to write a code for a "Dice generator" and I want it to generate random numbers (from 1-6) a x numbers of times.
The x number of times is given as a parameter by the user through the terminal, with this "$argc argv" function, but this is not really important.
What I want to know is: how do I generate random values x number of times?
FOR EXAMPLE:
User input: 4
Output: 5 3 6 8
User input: 3
Output: 5 1 2
This is what I am trying to write. I used the array_rand function with the array as a parameter, and the number of times I want as the second parameter, but It does not work! What am I not getting here?
<?php
if ($argc < 2) {
print "You have to write at least one parameter" .PHP_EOL;
exit(1);
}
//This is the variable that corresponds to the number of times the user will give on the Terminal as a parameter.
//$randoms = $argv[1];
$num = 3;
$diceNumbers = [1, 2, 3, 4, 5, 6];
$keys = array_rand($diceNumbers, $num);
print $diceNumbers[$keys[0]]." ".$diceNumbers[$keys[1]] .PHP_EOL;
?>
Given your use case is for a 'dice roll' I wonder if you would be better off using a cryptographically secure random number generation function like random_int() rather than array_rand(), which is not.
You can then use a for loop for your output as you know in advance how many times you want the loop to run.
$num = 3;
for($i = 0; $i < $num; $i++){
print random_int(1,6) . PHP_EOL;
}
The array_rand(arry, n) function returns an array with length n, composed of elements from arry. It looks like you did everything right, however when you print it you only ask for the first 2 random numbers. If you want to print all of the numbers, you will need a for/foreach loop.
foreach($keys as $key) {
print $key . " ";
}
I'm generating a unique 5 digit code using the following.
$randomUniqueNumber = rand(10000,99999);
I need to change this to an alphanumeric number with 5 digits and 2 letters.
The below gives me an alphanumeric number, but not restricted to just 2 letters.
$generated = substr(md5(rand()),0,5);
How would I generate a random string with 5 digits, and two letters?
There are probably a few ways to do it, but the following is verbose to get you going.
<?php
// define your set
$nums = range(0, 9);
$alphas = range('a', 'z');
// shuffle sets
shuffle($nums);
shuffle($alphas);
// pick out only what you need
$nums = array_slice($nums, 0, 5);
$alphas = array_slice($alphas, 0, 2);
// merge them together
$set = array_merge($nums, $alphas);
// shuffle
shuffle($set);
// create your result
echo implode($set); //86m709g
https://3v4l.org/CV7fS
Edit:
After reading I'm generating a unique 5 digit code using the following. I suggest, instead, create your string by changing the base from an incremented value, rather than random (or shuffled) as you will undoubtedly get duplicates, and to achieve no dupes you would need to pre-generate and store your entire set of codes and pick from them.
Instead look at something like hashids.
I am generating random numbers using php random function, but I want the generated number should be unique and it should not be repeated again.
----------
php code
$number = rand(100,100000); //a six digit random number between 100 to 100000
echo $number;
----------
but I am using this function for multiple times in my code for users so at very rare case there should be a chance of generating same number again. how can i avoid that.
I would do this:
You said you have branches. The receipt id could look something like this:
$dateString = date('Ymd'); //Generate a datestring.
$branchNumber = 101; //Get the branch number somehow.
$receiptNumber = 1; //You will query the last receipt in your database
//and get the last $receiptNumber for that branch and add 1 to it.;
if($receiptNumber < 9999) {
$receiptNumber = $receiptNumber + 1;
}else{
$receiptNumber = 1;
}
Update the receipt database with the receipt number.
$dateString . '-' . $branchNumber . '-' . $receiptNumber;
This will read:
20180406-101-1
This will be unique(Provided you do less than 10,000 transactions a day.) and will show your employees easily readable information.
If you are storing users in DB you should create column [ID] as primary key with auto increment and that would be best solution.
In other case I'd recommend you to simply store all user id's in ascending order from N to M by reading last ID and adding 1 to it because I see no real gain from random order that only adds complexity to your code.
There are many ways, example:
$freq = [];
$number = rand(100,100000);
$times = 10;
while($times-- > 0)
{
while(in_array($number, $freq))$number = rand(100,100000);
$freq[] = $number;
echo $number . "<br>";
}
This will print 10 random unique numbers.
random_int
(PHP 7)
<?php
$number = random_int(100, 100000);
echo $number;
All you need to do is use timestamp in php as timestamp never cross each other hence it will always generate unique number.You can use time() function in php.
The time() function is used to format the timestamp into a human desired format. The timestamp is the number of seconds between the current time and 1st January, 1970 00:00:00 GMT. It is also known as the UNIX timestamp.
<?php
$t=time();
echo $t;
?>
Also you add a rand() function and insert it in front of the $t to make it more random as if few users work at same time then the timestamp might collide.
<?php
$number = rand(100,100000);
$t=time();
$random = $number.''.$t;
echo $random;
?>
The above will reduce the chance to timestamp collide hence making the probability of number uniqueness almost 100%.
And if you make your column unique in your database then the php wont insert the number hence this bottleneck will ensure you will always get a unique random number.
bill_id not null unique
If you are using it for something like user id, then you can use uniqid for that. This command gets a prefixed unique identifier based on the current time in microseconds.
Here's how to use it:
string uniqid ([ string $prefix = "" [, bool $more_entropy = FALSE]] )
Where prefix is used if you are generating ids for a lot if hosts at the same time, you can use this to differentiate between various hosts if id is generated at the same microsecond.
more_entropy increases the likeness of getting unique values.
Usage:
<?php
/* A uniqid, like: 4b3403665fea6 */
printf("uniqid(): %s\r\n", uniqid());
/* We can also prefix the uniqid, this the same as
* doing:
*
* $uniqid = $prefix . uniqid();
* $uniqid = uniqid($prefix);
*/
printf("uniqid('php_'): %s\r\n", uniqid('php_'));
/* We can also activate the more_entropy parameter, which is
* required on some systems, like Cygwin. This makes uniqid()
* produce a value like: 4b340550242239.64159797
*/
printf("uniqid('', true): %s\r\n", uniqid('', true));
?>
this code must work
some description about code:
generate unique id
extract numbers form unique id with regex
gathering numbers from regex with a loop
<?php
$unique = uniqid("",true);
preg_match_all("!\d+!", $unique ,$matches);
print_r($matches);
$numbers = "";
foreach($matches[0] as $key => $num){
$numbers .= $num;
}
echo $numbers;
How can I generate a 6 digit unique number? I have verification mechanisms in place to check for duplicate entries.
$six_digit_random_number = random_int(100000, 999999);
As all numbers between 100,000 and 999,999 are six digits, of course.
If you want it to start at 000001 and go to 999999:
$num_str = sprintf("%06d", mt_rand(1, 999999));
Mind you, it's stored as a string.
Another one:
str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
Anyway, for uniqueness, you will have to check that your number hasn't been already used.
You tell that you check for duplicates, but be cautious since when most numbers will be used, the number of "attempts" (and therefore the time taken) for getting a new number will increase, possibly resulting in very long delays & wasting CPU resources.
I would advise, if possible, to keep track of available IDs in an array, then randomly choose an ID among the available ones, by doing something like this (if ID list is kept in memory):
$arrayOfAvailableIDs = array_map(function($nb) {
return str_pad($nb, 6, '0', STR_PAD_LEFT);
}, range(0, 999999));
$nbAvailableIDs = count($arrayOfAvailableIDs);
// pick a random ID
$newID = array_splice($arrayOfAvailableIDs, mt_rand(0, $nbAvailableIDs-1), 1);
$nbAvailableIDs--;
You can do something similar even if the ID list is stored in a database.
Here's another one:
substr(number_format(time() * rand(),0,'',''),0,6);
There are some great answers, but many use functions that are flagged as not cryptographically secure. If you want a random 6 digit number that is cryptographically secure you can use something like this:
$key = random_int(0, 999999);
$key = str_pad($key, 6, 0, STR_PAD_LEFT);
return $key;
This will also include numbers like 000182 and others that would otherwise be excluded from the other examples.
You can also use a loop to make each digit random and generate random number with as many digits as you may need:
function generateKey($keyLength) {
// Set a blank variable to store the key in
$key = "";
for ($x = 1; $x <= $keyLength; $x++) {
// Set each digit
$key .= random_int(0, 9);
}
return $key;
}
For reference, random_int — Generates cryptographically secure pseudo-random integers that are suitable for use where unbiased results are critical, such as when shuffling a deck of cards for a poker game." - php.net/random_int
<?php
$file = 'count.txt';
//get the number from the file
$uniq = file_get_contents($file);
//add +1
$id = $uniq + 1 ;
// add that new value to text file again for next use
file_put_contents($file, $id);
// your unique id ready
echo $id;
?>
i hope this will work fine. i use the same technique in my website.
In PHP 7.0+ I would suggest random_int($min, $max) over mt_rand().
$randomSixDigitInt = \random_int(100000, 999999);
From php.net:
Caution
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.
So this depends mostly on context. I'll also add that as of PHP 7.1.0 rand() is now an alias to mt_rand().
Cheers
$characters = '123456789';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < 6; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$pin=$randomString;
This will generate random 6 digit number
<?php
mt_rand(100000,999999);
?>
I would use an algorithm, brute force could be as follows:
First time through loop:
Generate a random number between 100,000 through 999,999 and call that x1
Second time through the loop
Generate a random number between 100,000 and x1 call this xt2, then generate a random number between x1 and 999,999 call this xt3, then randomly choose x2 or x3, call this x2
Nth time through the loop
Generate random number between 100,000 and x1, x1 and x2, and x2 through 999,999 and so forth...
watch out for endpoints, also watch out for x1
<?php echo rand(100000,999999); ?>
you can generate random number
You can use $uniq = round(microtime(true));
it generates 10 digit base on time
which is never be duplicated
Try this using uniqid and hexdec,
echo hexdec(uniqid());
Among the answers given here before this one, the one by "Yes Barry" is the most appropriate one.
random_int(100000, 999999)
Note that here we use random_int, which was introduced in PHP 7 and uses a cryptographic random generator, something that is important if you want random codes to be hard to guess. random_bytes was also introduced in PHP 7 and likewise uses a cryptographic random generator.
Many other solutions for random value generation, 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.
The code above generates a string of 6 decimal digits. If you want to use a bigger character set (such as all upper-case letters, all lower-case letters, and the 10 digits), this is a more involved process, but you have to use random_int or random_bytes rather than rand(), mt_rand(), str_shuffle(), etc., if the string will serve as a password, a "confirmation code", or another secret value. See an answer to a related question, and see also: generating a random code in php?
I also list other things to keep in mind when generating unique identifiers, especially random ones.
This is the easiest method to generate 6 digits random number
$data = random_int(100000, 999999);
echo $data;
Is there is any way to avoid duplication in random number generation .
I want to create a random number for a special purpose. But it's should be a unique value. I don't know how to avoid duplicate random number
ie, First i got the random number like 1892990070. i have created a folder named that random number(1892990070). My purpose is I will never get that number in future. I it so i have duplicate random number in my folder.
A random series of number can always have repeated numbers. You have to keep a record of which numbers are already used so you can regenerate the number if it's already used. Like this:
$used = array(); //Initialize the record array. This should only be done once.
//Do like this to draw a number:
do {
$random = rand(0, 2000);
}while(in_array($random, $used));
$used[] = $random; //Save $random into to $used array
My example above will of course only work across a single page load. If it should be static across page loads you'll have to use either sessions (for a single user) or some sort of database (if it should be unique to all users), but the logic is the same.
You can write a wrapper for mt_rand which remembers all the random number generated before.
function my_rand() {
static $seen = array();
do{
$rand = mt_rand();
}while(isset($seen[$rand]));
$seen[$rand] = 1;
return $rand;
}
The ideas to remember previously generated numbers and create new ones is a useful general solution when duplicates are a problem.
But are you sure an eventual duplicate is really a problem? Consider rolling dice. Sometimes they repeat the same value, even in two sequential throws. No one considers that a problem.
If you have a controlled need for a choosing random number—say like shuffling a deck of cards—there are several approaches. (I see there are several recently posted answer to that.)
Another approach is to use the numbers 0, 1, 2, ..., n and modify them in some way, like a Gray Code encoding or exclusive ORing by a constant bit pattern.
For what purpose are you generating the random number? If you are doing something that generates random "picks" of a finite set, like shuffling a deck of cards using a random-number function, then it's easiest to put the set into an array:
$set = array('one', 'two', 'three');
$random_set = array();
while (count($set)) {
# generate a random index into $set
$picked_idx = random(0, count($set) - 1);
# copy the value out
$random_set []= $set[$picked_idx];
# remove the value from the original set
array_splice($set, $picked_idx, 1);
}
If you are generating unique keys for things, you may need to hash them:
# hold onto the random values we've picked
$already_picked = array();
do {
$new_pick = rand();
# loop until we know we don't have a value that's been picked before
} while (array_key_exists($new_pick, $already_picked));
$already_picked[$new_pick] = 1;
This will generate a string with one occurence of each digit:
$randomcharacters = '0123456789';
$length = 5;
$newcharacters = str_shuffle($randomcharacters);
$randomstring = substr($newcharacters, 0, $length);