1
\$\begingroup\$

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;
    }
}
\$\endgroup\$
8
\$\begingroup\$

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;
}
\$\endgroup\$
3
\$\begingroup\$

This is really pointless:

if (in_array($role, $admins)) {
    return true;
} else {
    return false;
}

when you can just call

return in_array($role, $admins);

So:

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

    $role = get_current_user_role();
    $admins = array(
        'Administrator',
        'Agent',
        'Contributor',
    );

    return in_array($role, $admins);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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