Drupal 7: Programmatically add/update users using user_save()

Here’s a quick code snippet I use to programmatically create new users:

<?php
$newUser = array(
  'name' => 'username',
  'pass' => 'password', // note: do not md5 the password
  'mail' => 'email address',
  'status' => 1,
  'init' => 'email address'
);
user_save(null, $newUser);
?>

And here’s how you can update an existing user:

<?php
// load user object
$existingUser = user_load('USERID');

// update some user property
$existingUser->some_property = 'blah';

// save existing user
user_save((object) array('uid' => $existingUser->uid), (array) $existingUser);

?>

If you wanted to update an existing user’s profile data:

<?php
// load user object
$existingUser = user_load('USERID');

// create an array of properties to update
$edit = array(
  'profile_first_name' => 'Eric'
);

// save existing user
user_save(
  (object) array('uid' => $existingUser->uid),
  $edit,
  'Personal Information' // category
);
?>

In Drupal 7:

<?php
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');

$account = new StdClass();
$account->is_new = TRUE;
$account->status = TRUE;
$account->name = 'someusername';
$account->pass = user_hash_password('somepassword');
$account->mail = 'email@example.com';
$account->init = 'email@example.com';
$account->roles[5] = 'some role';
$account->field_first_name[LANGUAGE_NONE][0]['value'] = 'some first name';
$account->field_last_name[LANGUAGE_NONE][0]['value'] = 'some last name';
user_save($account);

?>

Updated: