Let's say I have an array of usernames as such:
[
'john.doe',
'john.doe1',
'john.doe2',
'john.doe4',
'john.doe5'
]
Now a new user registers as john.doe. I have fetched the already existing john.doe's from the DB using a LIKE query and stored in the array above. Then I want to iterate over that array to see which spot is available for the newly registered john.doe.
In this case the available spot would be john.doe3.
I know how to do this using a while loop and simply adding an increment until there's no match.
Basically I have two questions:
Is this the right way of approaching this duplicate username issue altogether?
I was wondering if maybe there's a better way in lieu of using the while loop?
Nope - better to use an identity token, consider adding a third value such as: md5('username'.'date')
or md5('username'.'fullname')
and then you can use this identifier for the specific user.
The better practice will be to use only the user row id for relations and for any query and the only step you use the username ( + password) is at login.
Here you go:
//without while:
/* NOT TESTED */
/* $uname -> is the username requested without the duplicate number */
function find_aspot($arr, $uname) {
natsort($arr);
if (empty($arr) || $arr[0] !== $uname) return $uname;
foreach($arr as $key => $data) {
$cur = str_replace($uname,'',$data);
$cur = ($cur === '')?0:intval($cur);
if (!isset($arr[$key+1])) break;
$next = intval(str_replace($uname,'',$arr[$key+1]))
if ($cur+1 !== $next) break;
}
return $uname.($cur+1);
}