Reputation: 299
I need to generate a random 4 digit number, but exclude 8 and 9 in the generation.
Here's the code I'm using now, but it obviously doesn't exclude 8 and 9,
rand(pow(10, 4 - 1), pow(10, 4) - 1);
Upvotes: 1
Views: 1023
Reputation: 15301
This would work as well.
$allowedNumbers = range(0, 7);
$digits = array_rand($allowedNumbers, 4);
$number = '';
foreach($digits as $d){
$number .= $allowedNumbers[$d];
}
echo $number;
Benefit here is you can specify the allowed characters by creating an array of allowed digits. It would also allow you to include really any character from an array including letters or words.
Upvotes: 3
Reputation: 8583
Something like?
$randomNumber = rand(0,7) . rand(0,7) . rand(0,7) . rand(0,7);
Upvotes: 2
Reputation: 59681
This should work for you:
Here I just get the random number with mt_rand()
then I convert it to base 8 (0-7
, means no 8 or 9) with base_convert()
. And at the end I simply take the first 4 digits with substr()
.
echo $number = substr(base_convert(mt_rand(), 10, 8), 0, 4);
Upvotes: 2