I'm using the PHP code seen at the bottom of this post to get the user's role from user ID. It works, but fails if the user role has been changed after registering. I've been looking for ages trying to find out how WordPress changes roles and why this would cause the below code to not work but am now lost.
Update: The error I get is
Warning:
array_key_exists()
expects parameter 2 to be array
$user = get_userdata( $user_id );
$capabilities = $user->{$wpdb->prefix . 'capabilities'};
if ( !isset( $wp_roles ) )
$wp_roles = new WP_Roles();
foreach ( $wp_roles->role_names as $role => $name ) :
if ( array_key_exists( $role, $capabilities ) )
echo $role;
endforeach;