Just wondering if my

else {return false;} 

statements are superfluous... do I just need one return true; here?

function has_access() {
    if ( is_user_logged_in() ) {
        $role = get_current_user_role();
        $admins = array(
            'Administrator',
            'Agent',
            'Contributor',
        );

        if (in_array($role, $admins)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
link|improve this question

feedback

2 Answers

up vote 5 down vote accepted

I'd replace the conditions with guard clauses. (Flattening Arrow Code)

function has_access() {
    if ( !is_user_logged_in() ) {
        return false;
    }
    $role = get_current_user_role();
    $admins = array(
        'Administrator',
        'Agent',
        'Contributor',
    );

    if (in_array($role, $admins)) {
        return true;
    }
    return false;
}
link|improve this answer
feedback
function has_access() {
    if (is_user_logged_in()) {
        $admins = array(
            'Administrator',
            'Agent',
            'Contributor',
        );
        return in_array(get_current_user_role(), $admins);
    }
   return false;
}
link|improve this answer
Both answers, yours and palacsint's, are correct. But I like the way you did yours better :) It's much cleaner and keeps with the "sentence" structure this code has attempted to implement +1 – showerhead May 4 at 15:31
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.