How to Use Multiple Conditions in a Single If Statement

November 2, 2012

This is certainly elementary programming knowledge, but bears repeating here. The scenario is that you need to check multiple cases in order to execute a certain piece of code. The scenario might be if you have multiple levels of permissions and need to allow the page (or certain parts of the page) to be visible for some and not other users. This is particularly important if you are checking multiple columns or tables in the database.

Let’s say you have a super-admin who is able to see everything on every page. But there might be certain things (like writing an article in a blog) which he shouldn’t be able to write from, lest he edit an article written by someone and his edits not show up as his own.

In this instance, you will need to check something like this:

if ($superadmin && $page_name != 'not my page'){

// User may edit this page.

}

Now let’s say that the user is super-admin of only part of the website, but not allowed to edit another part. In this case, you’ll need to double up the conditions. Now add in a second category of users who must also be in the same assigned group as the super-admin.

if ( ($superadmin && $page_name !="not my page") || ($regular_user && $page_name =="my page")) {
// User can edit the code here.
}

This may seem very basic, but the important part to remember is that the nested if statements make checking permissions much easier. You could use nested if statements to accomplish the same thing, but it's all about getting your code concise and readable. Adding too many levels of if statements makes it hard to read the code, so this approach is much cleaner.

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive