Could not generate 6 digit random number including date time using PHP - php

I need one help . I need to generate random number including date and time using PHP. I am explaining my code below.
$random=generateRandom();
echo $random;
function generateRandom() {
$result = base_convert((float) rand() / (float) getrandmax() * round(microtime(true) * 1000),6, 36);
return $result;
}
The above function giving the 3 digit output. Here i need to generate up to 6 digit. Please help me.

Here it is with microtime :
$random=generateRandom();
echo $random;
function generateRandom() {
$numbers = str_split((string)(int)microtime(true));
shuffle($numbers);
$rand = '';
foreach (array_rand($numbers, 6) as $k) $rand .= $numbers[$k];
return $rand;
}
Conversion are here to eliminated the dot character.

Related

Laravel format to 1 decimal place

#if($user->dettagli->facebook_follower >= 1000 && $user->dettagli->facebook_follower <= 999999)
<?php
echo(round($user->dettagli->facebook_follower, 5,PHP_ROUND_HALF_DOWN) . "K");
?>
{{$user->dettagli->facebook_follower / 1000}} K
#endif
Hi could someone please help me. I am using Laravel and trying to display a users Facebook follower count, but I got a little stuck with something. I am taking their int at for example 1589 followers and trying to return in the blade "1.5k". On screen I return either 1589k with this php call or 1.589k. How do I get that number to one decimal place and become only 1.5k??
thank you!
As per the docs
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
You are specifying a precision of 5. You should change this to 1.
Change your function call to:
echo(round($user->dettagli->facebook_follower, 1, PHP_ROUND_HALF_DOWN) . "K");
EDIT: I mis-read the question. This is a function that should handle numbers into the millions.
You would need to use laravel-twigbridge to make the function available in your templates though.
function pretty_number(int $n): string {
$prettyN = $n;
$suffix = '';
$len = strlen((string) $n);
$suffixes = ['K', 'M'];
foreach ($suffixes as $s) {
if ($n < 1000) {
break;
}
$suffix = $s;
$n = $n / 1000;
$prettyN = number_format($n, 1);
}
return $prettyN . $suffix;
}
echo pretty_number(100); // 100
echo pretty_number(999); // 99
echo pretty_number(1589); // 1.6K
echo pretty_number(1600); // 1.6K
echo pretty_number(1589300); // 1.6M
You can use the NumberFormatter. This can be defined in a global place so you only need to use the third line in your blade view.
$a = new \NumberFormatter("en-US", \NumberFormatter::DECIMAL);
$a->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 1);
echo $a->format($user->dettagli->facebook_follower);

How to randomly generate a number from a range of numbers but exclude some numbers? [duplicate]

This question already has answers here:
PHP rand() exclude certain numbers
(10 answers)
Closed 6 years ago.
How would I generate a random number from a range of numbers between 1 and 10 while excluding an array of numbers e.g. 4,5,6.
$exclude = array(4,5,6);
The following code allows to generate random numbers within a range however only for a single number and not an array of numbers
function randnumber() {
do {
$numb = rand(1,10);
} while ($varr == 4);
return $numb;
}
Create a loop that iterates until a generated random number using rand function is not in array. If the generated number is found in array, again another random number is generated.
do {
$number = rand(1,10);
} while(in_array($number, array(4,5,6)));
echo $number;
or
while(in_array(($number = rand(1,10)), array(4,5,6)));
echo $number;
You can use it like a function too:
<?php
function randomNo($min,$max,$arr) {
while(in_array(($number = rand($min,$max)), $arr));
return $number;
}
echo randomNo(1,10,array(4,5,6));
The above function, does the same process, in addition, you can reuse the code. It gets minimum and maximum number and the array of values to exclude.
Finally,
without loop, but with recursive function. The function generates a random number and returns if it is not found in the exclude array:
function randomExclude($min, $max, $exclude = array()) {
$number = rand($min, $max);
return in_array($number, $exclude) ? randomExclude($min, $max, $exclude) : $number;
}
echo randomExclude(1,10,array(4,5,6));
<?php
$exclude = array(4,5,6); // The integers to excluded
do
{
$x = rand(1, 10); // Generate a random integer between 1 and 10
}while(in_array($x, $exclude)); // If we hit something to exclude, try again
echo $x; // A random integer not excluded
?>
It would be wise to check if not all inputs are excluded to avoid infinite loops
You can simply do this, using array functions like this:
function my_rand($min, $max, array $exclude = array())
{
$range = array_diff(range($min, $max), $exclude);
array_shuffle($range);
return array_shift($range);
}
Some time ago I also wanted to become rid of these nasty little while loops. Reduced to fit your version of the problem, my approach would be to:
first generate a random number which in range (10 - 3) to indicate the position of the number to be generated in the hypothetical list of numbers in the desired range excluding {4,5,6}
second increment this value by the lower range (1)
third increment by 1 for every number in the set {4,5,6} it is equal to or greather (in order from the smallest to the highest number in that set)
So, all in all I'd basically stretch and blurr the hypothetical set of numbers the generated random value can be to fit into the possible outcomes.
$total = range(0,10);
$exclude = range(4,6);
$include = array_diff($total, $exclude);
print_r (array_rand($include));

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.

How to round down to the nearest significant figure in php

Is there any slick way to round down to the nearest significant figure in php?
So:
0->0
9->9
10->10
17->10
77->70
114->100
745->700
1200->1000
?
$numbers = array(1, 9, 14, 53, 112, 725, 1001, 1200);
foreach($numbers as $number) {
printf('%d => %d'
, $number
, $number - $number % pow(10, floor(log10($number)))
);
echo "\n";
}
Unfortunately this fails horribly when $number is 0, but it does produce the expected result for positive integers. And it is a math-only solution.
Here's a pure math solution. This is also a more flexible solution if you ever wanted to round up or down, and not just down. And it works on 0 :)
if($num === 0) return 0;
$digits = (int)(log10($num));
$num = (pow(10, $digits)) * floor($num/(pow(10, $digits)));
You could replace floor with round or ceil. Actually, if you wanted to round to the nearest, you could simplify the third line even more.
$num = round($num, -$digits);
If you do want to have a mathy solution, try this:
function floorToFirst($int) {
if (0 === $int) return 0;
$nearest = pow(10, floor(log($int, 10)));
return floor($int / $nearest) * $nearest;
}
Something like this:
$str = (string)$value;
echo (int)($str[0] . str_repeat('0', strlen($str) - 1));
It's totally non-mathy, but I would just do this utilizing sting length... there's probably a smoother way to handle it but you could acomplish it with
function significant($number){
$digits = count($number);
if($digits >= 2){
$newNumber = substr($number,0,1);
$digits--;
for($i = 0; $i < $digits; $i++){
$newNumber = $newNumber . "0";
}
}
return $newNumber;
}
A math based alternative:
$mod = pow(10, intval(round(log10($value) - 0.5)));
$answer = ((int)($value / $mod)) * $mod;
I know this is an old thread but I read it when looking for inspiration on how to solve this problem. Here's what I came up with:
class Math
{
public static function round($number, $numberOfSigFigs = 1)
{
// If the number is 0 return 0
if ($number == 0) {
return 0;
}
// Deal with negative numbers
if ($number < 0) {
$number = -$number;
return -Math::sigFigRound($number, $numberOfSigFigs);
}
return Math::sigFigRound($number, $numberOfSigFigs);
}
private static function sigFigRound($number, $numberOfSigFigs)
{
// Log the number passed
$log = log10($number);
// Round $log down to determine the integer part of the log
$logIntegerPart = floor($log);
// Subtract the integer part from the log itself to determine the fractional part of the log
$logFractionalPart = $log - $logIntegerPart;
// Calculate the value of 10 raised to the power of $logFractionalPart
$value = pow(10, $logFractionalPart);
// Round $value to specified number of significant figures
$value = round($value, $numberOfSigFigs - 1);
// Return the correct value
return $value * pow(10, $logIntegerPart);
}
}
While the functions here worked, I needed significant digits for very small numbers (comparing low-value cryptocurrency to bitcoin).
The answer at Format number to N significant digits in PHP worked, somewhat, though very small numbers are displayed by PHP in scientific notation, which makes them hard for some people to read.
I tried using number_format, though that needs a specific number of digits after the decimal, which broke the 'significant' part of the number (if a set number is entered) and sometimes returned 0 (for numbers smaller than the set number).
The solution was to modify the function to identify really small numbers and then use number_format on them - taking the number of scientific notation digits as the number of digits for number_format:
function roundRate($rate, $digits)
{
$mod = pow(10, intval(round(log10($rate))));
$mod = $mod / pow(10, $digits);
$answer = ((int)($rate / $mod)) * $mod;
$small = strstr($answer,"-");
if($small)
{
$answer = number_format($answer,str_replace("-","",$small));
}
return $answer;
}
This function retains the significant digits as well as presents the numbers in easy-to-read format for everyone. (I know, it is not the best for scientific people nor even the most consistently length 'pretty' looking numbers, but it is overall the best solution for what we needed.)

How to generate an alphanumeric incrementing id in PHP?

I have system in PHP in which I have to insert a Number which has to like
PO_ACC_00001,PO_ACC_00002,PO_ACC_00003.PO_ACC_00004 and so on
this will be inserted in Database for further reference also "PO and ACC" are dynamic prefix they could different as per requirement
Now my main concern is how can is increment the series 00001 and mantain the 5 digit series in the number?
>> $a = "PO_ACC_00001";
>> echo ++$a;
'PO_ACC_00002'
You can get the number from the string with a simple regex, then you have a simple integer.
After incrementing the number, you can easily format it with something like
$cucc=sprintf('PO_ACC_%05d', $number);
Create a helper function and a bit or error checking.
/**
* Takes in parameter of format PO_ACC_XXXXX (where XXXXX is a 5
* digit integer) and increment it by one
* #param string $po
* #return string
*/
function increment($po)
{
if (strlen($po) != 12 || substr($po, 0, 7) != 'PO_ACC_')
return 'Incorrect format error: ' . $po;
$num = substr($po, -5);
// strip leading zero
$num = ltrim($num,'0');
if (!is_numeric($num))
return 'Incorrect format error. Last 5 digits need to be an integer: ' . $po;
return ++$po;
}
echo increment('PO_ACC_00999');
Sprintf is very useful in situations like this, so I'd recommend reading more about it in the documentation.
<?php
$num_of_ids = 10000; //Number of "ids" to generate.
$i = 0; //Loop counter.
$n = 0; //"id" number piece.
$l = "PO_ACC_"; //"id" letter piece.
while ($i <= $num_of_ids) {
$id = $l . sprintf("%05d", $n); //Create "id". Sprintf pads the number to make it 4 digits.
echo $id . "<br>"; //Print out the id.
$i++; $n++; //Letters can be incremented the same as numbers.
}
?>

Categories