How to assign a user role Programmatically

If you need to assign a user role depending certain action Please follow the instruction below.
    global $user; 
    $uid = $user->uid;
    $user = user_load($uid);
    $role = user_role_load_by_name("role_name");
    $user->roles = $user->roles + array($role->rid => $role->name);
    user_save($user);

First of all load the user object as its a global variable hence word global, the object contain
stdClass Object
(
    [uid] =>
    [name] =>
    [pass] => 
    [mail] =>
    [theme] => 
    [signature] => 
    [signature_format] =>
    [created] =>
    [access] =>
    [login] =>
    [status] => 1
    [timezone] => UTC
    [language] => 
    [picture] => 0
    [init] => 
    [data] => 
    [sid] =>
    [ssid] => 
    [hostname] => 
    [timestamp] =>
    [cache] => 0
    [session] => 
    [roles] => Array
        (
            [2] => 
        )

)

Depending on your need you can any key from that object and grab the value. once you have the user id just add the new role to user role array, and call user_save. That should assign new role to the uid . please use this code on your own discretion
Category: