I need to create unique alphanumeric IDs, 6 characters long in PHP.
Although I have found a lot of answers solving this problem, I would like the letters to be positioned in specific place in the ID, for example A1B2C3 (first, third and fifth character).
My only solution for this is to create 6 "for" loops (a-z and 0-9 * 3 times) and insert the output in an array and then in MySQL table. There will definitely be no duplicates but is there any better way?
My code so far is:
<?php
$id=array();
for($a='A';$a!='AA';$a++){
for($b=1;$b<=9;$b++){
for($c='A';$c!='AA';$c++){
for($d=1;$d<=9;$d++){
for($e='A';$e!='AA';$e++){
for($f=1;$f<=9;$f++){
$id[]=$a.$b.$c.$d.$e.$f;
}
}
}
}
}
}
foreach ($id as $value) {
echo "$value \n";
}
?>
If you need sequential IDs:
// to start
//$numIds = 20000;
//$id = '';
// to add more
$numIds = 1000;
$id = 'A1J5M2'; // put MAX id from DB here
if ( '' !== $id ) { // increment id
list($aa, $bb, $cc, $dd, $ee, $ff) = str_split($id);
$arr = [$aa, $bb, $cc, $dd, $ee, $ff];
list($aa, $bb, $cc, $dd, $ee, $ff) = incc($arr, count($arr) - 1);
}
else {
list($aa, $bb, $cc, $dd, $ee, $ff) = ['A',1,'A',1,'A',1];
}
// generate ids
$ids = [];
for($a=$aa;$a!='AA';$a++){
for($b=$bb;$b<=9;$b++){
$bb = 1; // reseting b - f is necessary when adding more ids
for($c=$cc;$c!='AA';$c++){
$cc = 'A';
for($d=$dd;$d<=9;$d++){
$dd = 1;
for($e=$ee;$e!='AA';$e++){
$ee = 'A';
for($f=$ff;$f<=9;$f++){
$ff = 1;
$ids[] = "$a$b$c$d$e$f";
// break out of all loops when desired number is reached
if ( $numIds <= count($ids) ) { break 6; }
}}}}}}
// db setup
$conn = mysqli_connect('localhost', 'root', '', 'dbtest');
$insertstmt = mysqli_prepare($conn, 'INSERT INTO ids (id) VALUES (?)');
// insert ids
mysqli_stmt_bind_param($insertstmt, 's', $id);
mysqli_autocommit($conn, false);
foreach ( $ids as $id ) {
mysqli_stmt_execute($insertstmt);
}
mysqli_commit($conn);
mysqli_close($conn);
// function to increment given id, accommodates rolling over, e.g., A9 -> B1
function incc ($arr, $idx) {
if ( is_int(intval($arr[$idx])) ) {
if ( 9 == $arr[$idx] ) {
$arr[$idx] = 1;
$arr = incc($arr, --$idx); // recursing
}
else {
$arr[$idx]++;
}
}
else {
if ( 'Z' === $arr[$idx] ) {
$arr[$idx] = 'A';
$arr = incc($arr, --$idx);
}
else {
$ord = ord($arr[$idx]);
$ord++;
$arr[$idx] = chr($ord);
}
}
return $arr;
}