Q:

Programmatically assign user role

I have multiple roles on my website, and I want to assign a certain role to some users when they register to my site.  
How can I assign a specific role to new users programmatically when they submit their registration forms?
I have tried modules like logintoboggan, autoassignrole, but they provide a default user role on registration, when I want to assign role to specific users, not to all users signing up on my site.

A:

We also solved this task with the user_multiple_role_edit() function.
In our usecase we didn't react on the register-form but on a special menu-callback to create users on the fly.
First: Create a user
$user = new stdClass();
$user->name = $name;
$user->status = 1;
user_save($user);

Second: Assign the user to the role
$role = user_role_load_by_name("my custom role");
user_multiple_role_edit(array($user->uid), 'add_role', $role->rid);

A:

While you may not consider this to be "programmatic," you can use the Rules module to do this.
Install the module and create a new rule on the event "After saving a new user account."  For the action, you will want to set the user role to ABC (where ABC are the role(s) you want to assign).
You can limit the role to specific users by adding conditions.  For example, you can use the "Data comparison" condition to only apply the rule if the user has chosen a specific value on the registration form (detailed example: limit the rule to only those users who select "female" as their gender on registration).
You will have to create a rule for each condition/role combination you wish to award.  However, Rules is a widely used module and can be exported manually or with the Features module, giving you a lot of flexibility.

A:

This will make the default roles 4,5 and 6:
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id){
    $form['account']['roles']['#default_value'][] = '4';
    $form['account']['roles']['#default_value'][] = '5';
    $form['account']['roles']['#default_value'][] = '6';
}

