Create users programmatically

Drupal 8 :

 

Adding / Creating users programmatically

$lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
$user = \Drupal\user\Entity\User::create();
 

 
// The Basics
    $user->setUsername('monkpal');  // You could also just set this to "monkpal" or something...
    $user->setPassword('monkpal');
    $user->setEmail('emailid');
    $user->enforceIsNew();  // Set this to FALSE if you want to edit (resave) an existing user object
 
// Optional settings 
    $user->set("init", 'emailid');
    $user->set("langcode", $lang);
    $user->set("preferred_langcode", $lang);
    $user->set("preferred_admin_langcode", $lang);
    //$user->set("setting_name", 'setting_value');
    $user->activate();
 
// Save user
    $result = $user->save();