Programmatically create a user and assign a role
This code worked for me:

$new_user = array(
  'name' =&gt; $name,
  'pass' =&gt; $sifra, // note: do not md5 the password
  'mail' =&gt; $email,
  'status' =&gt; 1,
  'init' =&gt; $email,
  'roles' =&gt; array(
    DRUPAL_AUTHENTICATED_RID =&gt; 'authenticated user',
    3 =&gt; 'custom role',
  ),
);

// The first parameter is sent blank so a new user is created.
user_save('', $new_user);