duplicate entry for username
Something very simple like this, using user_load_by_name(), would be an option:

$original_username = $username = 'something';
$count = 1;
while (user_load_by_name($username)) {
  $username = $original_username . $count++;
}

$fields = array(
  'name' =&gt; $username,
  ...


That will keep on trying 'something', 'something1', 'something2', 'something3', etc. until it finds a unique name.