PHP Random X Digit Number

php random x digit number

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);

How can I generate a 6 digit unique number?

$six_digit_random_number = random_int(100000, 999999);

As all numbers between 100,000 and 999,999 are six digits, of course.

generate 14 digit random number in php

I won't get into a discussion about how "random" we can ever really get, I am pretty sure this will generate a number random enough! :)

function randomNumber($length) {
$result = '';
for($i = 0; $i < $length; $i++) {
$result .= mt_rand(0, 9);
}
return $result;
}

..and of course then it's just echo randomNumber(14);

rand(000000, 999999) sometimes generate 4 digit numbers

$num = rand(100000, 999999);

Maybe this do the job :)

Generate a 10 digit number for n times

First you have to use a for loop. A loop allows you to do something so many times you want.

for ($i = 1; $i <= 100; $i++) {
}

$i++ is called Post-increment it just sets $i + 1. So it's like $i = $i + 1.

Now put your random number string in the for loop.

<?php
for ($i = 1; $i <= 100; $i++) {
echo "06".mt_rand(0,9).mt_rand(0,9).mt_rand(0,9).mt_rand(0,9).mt_rand(0,9).mt_rand(0,9).mt_rand(0,9).mt_rand(0,9)."<br>";
}
?>

Don't forget to add a <br> at the end. It's a line break. If you want to use it in a textfile you have to use \n.

Generate a random 10 digit number and insert into mysql?

try to getting ten digit rand no

$randnum = rand(1111111111,9999999999);

Generate 7 digit number similar to original number in PHP

https://www.tehplayground.com/WJiQXDOWT5CR5SwS

$phone = "9876543";
function getSimilar($phone, $num) {
$out = array();
for( $x=0; $x<$num; $x++) {
$new = array();
$p = str_split($phone);
$ctr=2;
foreach ($p as $n) {
$neg = rand(0,10) > 5? 1:-1;
$n = abs((intVal($n) + ( rand(0,$ctr) * $neg)) );
$new[] = min($n,9);
$ctr++;
}
$out[]=implode("",$new);
}

return $out;

}

$nphone = getSimilar($phone, 5);
echo $phone . "\n";
print_r( $nphone);

example output:

Array
(
[0] => 9634999
[1] => 7988194
[2] => 9896724
[3] => 8949969
[4] => 8998434
)


Related Topics



Leave a reply



Submit