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?
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 || falsewhich is false.As a side note this also works with the
&&operator, but it stops evaluation when the first expression results in afalsevalue.