3

I'm creating a script which creates a random security number for a user, and I'm looking at ways I can complete this.

I need a security number with 7 digits but doesn't contain a 0. but when using rand(1111111,9999999) there is still a possibility of a 0 being inside of that number, I was wondering which loop would be best to check this and what function would I use to check for the existence of a 0 in the string?

4 Answers 4

5

This code should do what you need:

$num = '';
for ($i = 1; $i <= 7; $i++)
    $num .= rand(1, 9);
$num = (int) $num;

It randomly generates the digits one by one and builds a string with them. Then, it changes the string to an integer.

Sign up to request clarification or add additional context in comments.

Comments

4

Couldn't you concat a random number between 1 and 9 7 times?

rand(1,9)

Comments

1

Using while to check will not help as there will be total 9^7 cases. You don't know which case you will get next time. So better to use rand 7 times.

<?php 
function myRand($length){
$ans=0;
for($i=0;$i<$length;$i++){
$ans=$ans*10+rand(1,9);
}
return $ans;
}

echo myrand(7);
?>

Comments

0

Solution based on base 9.

$p = array();
$p[0] = 1;
for ($i=1; $i<=6; $i++):
    $p[$i] = $p[$i-1] * 9;
endfor;

$max = $p[6] * 9 - 1;
$rand = rand(0,$max);

$ret = array();
for ($i=6; $i>=0; $i--):
    $tmp = $rand / $p[$i];
    $tmp = floor($tmp);
    $rand = $rand - $p[$i] * $tmp;
    $ret[] = (string)($tmp + 1);
var_dump($tmp);
endfor;

$ret = implode($ret);
var_dump($ret);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.