duplicate entry for username I am creating a user account programmatically with the following code. 

$fields = array(
  'name' =&gt; $first_name,
  'mail' =&gt; $mail,
  'pass' =&gt; $password,
  'status' =&gt; 1,
  'init' =&gt; $mail,
);

$account = user_save('', $fields);


When I am trying with same name again, it throws an error, but by default it updates the name. 

How do I update the name if already exist?
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.