Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 398
Chris Armitage Avatar asked Aug 06 '11 16:08

Chris Armitage


People also ask

What does the confirm () method return?

The confirm() method displays a dialog box with a message, an OK button, and a Cancel button. The confirm() method returns true if the user clicked "OK", otherwise false .

What is confirm box return?

The confirm box is an advanced form of alert box. It is used to display message as well as return a value (true or false). The confirm box displays a dialog box with two buttons, OK and Cancel. When the user clicks on the OK button it returns true and when the user clicks on the Cancel button it returns false.

What are alert and confirm method in JavaScript?

JavaScript Message Boxes: alert(), confirm(), prompt() JavaScript provides built-in global functions to display messages to users for different purposes, e.g., displaying a simple message or displaying a message and take the user's confirmation or displaying a popup to take the user's input value.

How do you make a confirm box?

You can create a JavaScript confirmation box that offers yes and no options by using the confirm() method. The confirm() method will display a dialog box with a custom message that you can specify as its argument.


1 Answers

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.

like image 80
GWW Avatar answered Sep 28 '22 02:09

GWW