You check for the existance of a number, say 4567
, but you add 'A456714'
, so you won't find the number.
You can fix it like this:
$numbers = array();
// Loop while there aren't enough numbers
while (count($numbers) < 2000) {
$random_number = rand(1000, 9999);
$code = 'A'.$random_number.'14';
if (!in_array($code, $numbers)) {
// This adds the number to the array
$numbers[] = $code;
}
}
I must say, the solution by deceze is also very nice (nicer, actually). The difference is that in his solution, you won't have any double numbers at all to check for, so it's probably going to be faster most of the times.
The disadvantage is that you will have a relatively big array with 9000 numbers. For this specific situation, his solution might even be better, but if you select a smaller quantity of random numbers, or from a larger range, this (your own) solution might be better. If you want to select 100 random numbers from range(100, 1000000)
then this solution is probably better, since the chance of picking a double number is very small and checking it is quite lightweight.
It's hard to tell where the tipping point is, but for your current situation, I would pick his.