Hard to explain, and let me show an example.
I would use something like this:
// the username
$username = "foo";
// find all users like foo%
$q = mysql_query("SELECT * FROM users WHERE username LIKE '".$username."%' ORDER BY id DESC");
// no users
if (mysql_num_rows($q) == 0) {
// create $username
}
else {
$last_num = 0;
// find all foo users
while ($row = mysql_fetch_array($q)) {
// match foo + number
if (preg_match("/^".preg_quote($username)."+([0-9]+)$/i", $row['username'], $match)) {
// extract the number part
$num = (int) $match[1];
// set the highest number
if ($num > $last_num) $last_num = $num;
}
}
// append the highest number to the username
if ($last_num > 0) $username .= $last_num + 1;
// create $username
}