Frontliner
Frontliner

Reputation: 29

PHP: How to combine logical operators

I have been working on a website for quite sometime, Right now im mostly doing work around the forums. Here i have to tell php what to show and what not to show by certain conditions.

I use IF for this, I also have it to work however the code becomes messy in the way i do it(Stacking IF`s).

When im trying to combine logical operators it doesnt work. Im aware that you need todo something with parentheses though in this case im unsure where they should be placed.

if (
    isset($_SESSION['role']) && $_SESSION['role'] > 3 || 
    isset($_SESSION['username']) && $_SESSION['username'] == $topic['author']
):

It will only take the first condition and ignores the second one

Upvotes: 1

Views: 784

Answers (2)

Barmar
Barmar

Reputation: 780919

Put parentheses around the && expressions that tests whether a particular variable is set and then whether the value meets the criteria.

if ((isset($_SESSION['role']) && $_SESSION['role'] > 3) || 
    (isset($_SESSION['username']) && $_SESSION['username'] == $topic['author'])):

These parentheses aren't actually needed, since && has higher precedence than ||. But I recommend using parentheses in any complicated conditions like this, to make the intent clear.

Note that an || condition is true if either of the operands is true. So if role > 3, it ignores the second condition. And if username == author, it ignores the first condition.

If you don't want to ignore either condition, you should be using && rather than ||.

Upvotes: 3

treyBake
treyBake

Reputation: 6560

It will only take the first condition and ignores the second one

When you have an if statement that stacks multiple conditions

if (
    -- condition 1 -- ||
    -- condition 2 -- ||
    -- etc --
) {

it will break out further checks when a condition is the first to pass.

E.g.

if we had this $posted array

[
    'user' => 'treybake',
    'name' => null
]

and use this if

if (
    !empty($_POST['user']) && $_POST['user'] !== 0 || 
    !empty($_POST['name'])
) {
    echo 'hello, world';
}

we will see an output of

hello, world

this is because the check on $_POST['user'] passed. Remember that || is OR - they both don't have to be true, only one or t'other.

If you want to build a conditional of required checks, use && (AND).

However, I actually think this case is better off as separate if checks - easier to read and maintain, and less likely to go wrong.

Upvotes: 1

Related Questions