User registration form: Give username "username n+1" value, if and when n is already used I'm using the first &amp; last name in the user registration form to generate the username for the new user:

$firstname = $form_state['values']['field_firstname'][LANGUAGE_NONE][0]['value'];
$lastname = $form_state['values']['field_lastname'][LANGUAGE_NONE][0]['value'];
$username = $firstname.''.$lastname;
$result = db_query("SELECT COUNT(*) FROM {users} WHERE name = :name", array(':name' =&gt; $username));
$results_number = $result-&gt;rowCount();
if ($results_number == 0) {
    $form_state['values']['name'] = $username;
}
else {
    $i = 1;
    $username = $firstname.''.$lastname.''.$i;
    while ($results_number &gt; 0) {
        $result = db_query("SELECT COUNT(*) FROM {users} WHERE name = :name", array(':name' =&gt; $username));
        $results_number = $result-&gt;rowCount();
        $i++;
        $username = $firstname.''.$lastname.''.$i;
        $form_state['values']['name'] = $username;
    }
}


But I get an infinite loop. There is a problem with that while loop, any suggestions on the best way to fix that?
So here is what I used to increment the username's suffix by 1 if the initial value is not found:

function increment_string($str, $separator, $first = 1) {
    preg_match('/(.+)'.$separator.'([0-9]+)$/', $str, $match);
    return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first;
}

$username = $firstname . ' ' . $lastname;
$result = db_query("SELECT uid FROM {users} WHERE name = :name", array(':name' =&gt; $username));
$results_number = $result-&gt;rowCount();
    if ($results_number == 0) {
        $form_state['values']['name'] = $username;  
    }
    else {
    while ($results_number &gt;= 1) {
        $username = increment_string($username_to_store, ' ');
        $result = db_query('SELECT uid FROM {users} WHERE name LIKE :name_pattern', array(':name_pattern' =&gt; db_like($username)));
        $results_number = $result-&gt;rowCount();
    }
    $form_state['values']['name'] = $username;  
    }