Chris Armitage
Chris Armitage

Reputation: 369

Confirmation of OR (||) usage in a return command

I've come across some interesting usage of the || operator in a return command, and would appreciate it if someone could confirm exactly what is going on (if I understand it, I can use it myself in the future)

The code is

    return (
        empty($neededRole) ||
        strcasecmp($role, 'admin') == 0 ||
        strcasecmp($role, $neededRole) == 0
    );

$neededRole and $role are either null, 'admin' or 'manager'

I'm reading it as:
If $neededRole is empty, no further checks are needed. Return true (and stop checking)
If ($role == 'admin') then allow access, no matter the required role. Return true (and stop checking)
if ($role == $neededRole) then allow access. Return true (and stop checking)

I'm guessing that upon reaching a 'true' that the checking stops, and if it reached the end of the line without having a 'true', it will default to false.

Am I close to the mark?

Upvotes: 5

Views: 77

Answers (2)

RiaD
RiaD

Reputation: 47640

Yes, you are right

See an example in manual

// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());

Upvotes: 0

GWW
GWW

Reputation: 44131

Yes, you are correct. This is called short-circuit evaluation. The final return value if all the conditions evaluate to false will be false || false || false which is false.

As a side note this also works with the && operator, but it stops evaluation when the first expression results in a false value.

Upvotes: 7

Related Questions