I’ve been asked to generate all possible combinations in the range AA0000-ZZ9999(let’s call it folio), for each combination I also need a 8 digits unique ramdom number (let’s call it attcode), can’t be consecutive, I know that there are a lot of combinations and the process will be slow, but as I’m using the rand function, and I’ve to validate that every attcode has to be unique, it is making my code slower, so if is it possible (I know it is, just don’t know how), give me recommendations ’bout how can I improve this in my code
$alph = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1);
$code_cache = array();
foreach ($alph as $value1) {
foreach ($alph as $value2) {
for ($i = 0; $i <= 9; $i++) {
$n=$i;
if($i<10){
$n="000".$i;
}
elseif($i<100){
$n="00".$i;
}
elseif($i<1000){
$n="0".$i;
}
$code = rand(10000000, 99999999);
while(in_array($code, $code_cache)){
$code = rand(10000000, 99999999);
}
$code_cache[]=$code;
echo $value1.$value2.$n.'-'.$code.'<br/>';
}
}
}
OK, I’ve totally cracked it this time. I’m actually a bit pleased with myself on this one:
…and all without the insane memory usage my early attempts were generating. Seriously, it takes 24 bytes to store a 32 bit (4 byte!) integer in PHP.
Looking at the progress on my (pretty low spec) laptop, I’m estimating a 10 minute runtime from start to finish. This will decrease considerably if you don’t echo the results on the fly. I think. Although I’m not sure what you’d do with them instead without burning up memory or getting stuck on disk I/O.