PHP OR Operator
Summary: in this tutorial, you’ll learn about the PHP OR operator (||) and how to use it to build complex logical expressions.
Introduction to the PHP OR operator
The logical OR operator accepts two operands and returns true if either operand is true; otherwise, it returns false . In other words, the logical OR operator returns false if both operands are false .
To represent the logical OR operator, PHP uses either the or keyword or the || as follows:
expression1 or expression2
The following table illustrates the result of the or operator:
expression1 | expression2 | expression1 || expression2 |
---|---|---|
true | true | true |
true | false | true |
false | true | true |
false | false | false |
Note that the or , Or , and OR are the same because PHP keywords are case-insensitive.
The || and or operators return the same result. The only difference between the || and or operators are their precedences. The or operator has higher precedence than the || operator.
PHP OR operator examples
Suppose that you need to clear the cache of the website if the flag $exprired or $purge is set to true . To do that, you can use the logical OR operator as follows:
$expired = true; $purged = false; $clear_cache = $expired || $purged; var_dump($clear_cache);
Code language: HTML, XML (xml)
bool(true)
Code language: JavaScript (javascript)
Since $expired is true , the result of the OR operator is also true .
However, if you change the $expired to false , the result will be false as shown in the following example:
$expired = false; $purged = false; $clear_cache = $expired || $purged; var_dump($clear_cache);
Code language: HTML, XML (xml)
In practice, you often use the logical OR operator in the if, if-else, if-elseif, while, and do-while statements.
Short-circuiting
When the first operand is true , the logical OR operator knows that the result must be also true . In this case, it doesn’t evaluate the second operand. This process is called short-circuiting.
In practice, you often find that the or operator is used in the following pattern:
function_call() || die(message)
Code language: PHP (php)
If the function_call() returns true , it succeeded. PHP will never execute the second operand which is a call to the die() function. Otherwise, PHP will call the die() function with an error message.
function connect_to_db() < return false; > connect_to_db() || die('Cannot connect to the database.');
Code language: HTML, XML (xml)
Cannot connect to the database
In this example, the connect_to_db() function returns false , PHP calls the die() function that shows the error message.
The PHP OR gotchas
See the following example:
$result = false or true; var_dump($result);
Code language: HTML, XML (xml)
bool(false)
Code language: JavaScript (javascript)
In this example, you would expect that the $result is true because false or true expression returns true. However, it is not the case.
When evaluating the following statement:
$result = false or true;
Code language: PHP (php)
PHP evaluates the $result = false first and then the or operator second because the = operator has higher precedence than the or operator.
Notice that each operator has precedence. And PHP will evaluate the operators with the higher precedence before the ones with the lower precedence.
Technically, it is equivalent to the following:
($result = false) or true;
Code language: PHP (php)
Therefore, $result is assigned the false value.
To fix this, you need to use parentheses to change the order of evaluation:
$result = (false or true); var_dump($result);
Code language: HTML, XML (xml)
bool(true)
Code language: JavaScript (javascript)
Or you can use the || operator:
$result = false || true; var_dump($result);
Code language: HTML, XML (xml)
bool(true)
Code language: JavaScript (javascript)
Therefore, it’s a good practice to always use the || operator instead of the or operator.
Summary
- Use the PHP OR operator ( or , || ) to combine two expressions and returns true if either expression is true ; otherwise, it returns false .
- The logical OR operator is short-circuiting.
- Do use the || operator instead of the or operator.
And or precedence php
worth reading for people learning about php and programming: (adding extras to get highlighted code)
?php>
about the following example in this page manual:
Example#1 Logical operators illustrated
.
// «||» has a greater precedence than «or»
$e = false || true ; // $e will be assigned to (false || true) which is true
$f = false or true ; // $f will be assigned to false
var_dump ( $e , $f );
// «&&» has a greater precedence than «and»
$g = true && false ; // $g will be assigned to (true && false) which is false
$h = true and false ; // $h will be assigned to true
var_dump ( $g , $h );
?>
_______________________________________________end of my quote.
If necessary, I wanted to give further explanation on this and say that when we write:
$f = false or true; // $f will be assigned to false
the explanation:
«||» has a greater precedence than «or»
its true. But a more acurate one would be
«||» has greater precedence than «or» and than «=», whereas «or» doesnt have greater precedence than » default»>$f = false or true ;
If you find it hard to remember operators precedence you can always use parenthesys — «(» and «)». And even if you get to learn it remember that being a good programmer is not showing you can do code with fewer words. The point of being a good programmer is writting code that is easy to understand (comment your code when necessary!), easy to maintain and with high efficiency, among other things.
Evaluation of logical expressions is stopped as soon as the result is known.
If you don’t want this, you can replace the and-operator by min() and the or-operator by max().
c ( a ( false ) and b ( true ) ); // Output: Expression false.
c ( min ( a ( false ), b ( true ) ) ); // Output: Expression is false.
c ( a ( true ) or b ( true ) ); // Output: Expression true.
c ( max ( a ( true ), b ( true ) ) ); // Output: Expression is true.
?>
This way, values aren’t automaticaly converted to boolean like it would be done when using and or or. Therefore, if you aren’t sure the values are already boolean, you have to convert them ‘by hand’:
c ( min ( (bool) a ( false ), (bool) b ( true ) ) );
?>
This works similar to javascripts short-curcuit assignments and setting defaults. (e.g. var a = getParm() || ‘a default’;)
( $a = $_GET [ ‘var’ ]) || ( $a = ‘a default’ );
?>
$a gets assigned $_GET[‘var’] if there’s anything in it or it will fallback to ‘a default’
Parentheses are required, otherwise you’ll end up with $a being a boolean.
> > your_function () or return «whatever» ;
> ?>
doesn’t work because return is not an expression, it’s a statement. if return was a function it’d work fine. :/?php
This has been mentioned before, but just in case you missed it:
//If you’re trying to gat ‘Jack’ from:
$jack = false or ‘Jack’ ;
// Try:
$jack = false or $jack = ‘Jack’ ;
//The other option is:
$jack = false ? false : ‘Jack’ ;
?>
$test = true and false; —> $test === true
$test = (true and false); —> $test === false
$test = true && false; —> $test === false
NOTE: this is due to the first line actually being
due to «&&» having a higher precedence than «=» while «and» has a lower one
If you want to use the ‘||’ operator to set a default value, like this:
$a = $fruit || ‘apple’ ; //if $fruit evaluates to FALSE, then $a will be set to TRUE (because (bool)’apple’ == TRUE)
?>
instead, you have to use the ‘?:’ operator:
$a = ( $fruit ? $fruit : ‘apple’ ); //if $fruit evaluates to FALSE, then $a will be set to ‘apple’
?>
But $fruit will be evaluated twice, which is not desirable. For example fruit() will be called twice:
function fruit ( $confirm ) if( $confirm )
return ‘banana’ ;
>
$a = ( fruit ( 1 ) ? fruit ( 1 ) : ‘apple’ ); //fruit() will be called twice!
?>
But since «since PHP 5.3, it is possible to leave out the middle part of the ternary operator» (http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary), now you can code like this:
$a = ( $fruit ? : ‘apple’ ); //this will evaluate $fruit only once, and if it evaluates to FALSE, then $a will be set to ‘apple’
?>
But remember that a non-empty string ‘0’ evaluates to FALSE!
$fruit = ‘1’ ;
$a = ( $fruit ? : ‘apple’ ); //this line will set $a to ‘1’
$fruit = ‘0’ ;
$a = ( $fruit ? : ‘apple’ ); //this line will set $a to ‘apple’, not ‘0’!
?>
To assign default value in variable assignation, the simpliest solution to me is:
$v = my_function () or $v = «default» ;
?>
It works because, first, $v is assigned the return value from my_function(), then this value is evaluated as a part of a logical operation:
* if the left side is false, null, 0, or an empty string, the right side must be evaluated and, again, because ‘or’ has low precedence, $v is assigned the string «default»
* if the left side is none of the previously mentioned values, the logical operation ends and $v keeps the return value from my_function()
This is almost the same as the solution from [phpnet at zc dot webhop dot net], except that his solution (parenthesis and double pipe) doesn’t take advantage of the «or» low precedence.
NOTE: «» (the empty string) is evaluated as a FALSE logical operand, so make sure that the empty string is not an acceptable value from my_function(). If you need to consider the empty string as an acceptable return value, you must go the classical «if» way.
In PHP, the || operator only ever returns a boolean. For a chainable assignment operator, use the ?: «Elvis» operator.
JavaScript:
let a = false;
let b = false;
let c = true;
let d = false;
let e = a || b || c || d;
// e === c
$a = false ;
$b = false ;
$c = true ;
$d = false ;
$e = $a ?: $b ?: $c ?: $d ;
// $e === $c
?>
Credit to @egst and others for the insight. This is merely a rewording for (formerly) lost JavaScript devs like myself.
$res |= true ;
var_dump ( $res );
?>
does not/no longer returns a boolean (php 5.6) instead it returns int 0 or 1?php