Confirmation of using OR (||) in the return command

I came across some interesting use of || operator in the return command, and I would be grateful if someone could confirm exactly what is happening (if I understand this, I can use it myself in the future)

The code

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

$ needRole and $ role are either null or "admin" or "manager"

I read it like:
If $neededRoleempty, no further checks are required. Return true (and stop checking)
If ($role == 'admin'), then allow access, regardless of the required role. Return true (and stop checking)
if ($role == $neededRole)then allow access. Return true (and stop checking)

I assume that upon reaching the “truth” that the check stops, and if it reaches the end of the line without the “truth”, it will default to false.

Am I close to the sign?

+5
source share
2 answers

Yes you are right. This is called a short circuit rating . The final return value, if all conditions evaluate to false, will be false || false || false, which is false.

&&, , false.

+7

,

. 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());
0

All Articles