Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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;
    }
}
share|improve this question

3 Answers

up vote 6 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;
}
share|improve this answer
function has_access() {
    if (is_user_logged_in()) {
        $admins = array(
            'Administrator',
            'Agent',
            'Contributor',
        );
        return in_array(get_current_user_role(), $admins);
    }
   return false;
}
share|improve this answer
1  
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 – mseancole May 4 '12 at 15:31

How about:

function has_access() {
    if (!is_user_logged_in())
        return false;

    return in_array(get_current_user_role(), array(
        'Administrator',
        'Agent',
        'Contributor'
    ));
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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