PHP 8.2.4 Released!


名前 結果
$a and $b 論理積 $a および $b が共に true の場合に true
$a or $b 論理和 $a または $b のどちらかが true の場合に true
$a xor $b 排他的論理和 $a または $b のどちらかが true でかつ両方とも true でない場合に true
! $a 否定 $atrue でない場合 true
$a && $b 論理積 $a および $b が共に true の場合に true
$a || $b 論理和 $a または $b のどちらかが true の場合に true

"and" および "or" 演算子が 2 種類あるのは、演算が行われる際の優先順位が 異なっているためです (演算子の優先順位 を参照ください)。

例1 論理演算子についての説明


// --------------------
// foo() は決してコールされることはありません。これらの演算子は短絡評価を行うからです。

$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());

// --------------------
// "||" の優先順位は "or" より高くなります

// $e に代入されるのは、(false || true) の評価結果です
// これは、次の式と同様です: ($e = (false || true))
$e = false || true;

// $f に false を代入してから "or" 演算子を評価します
// これは、次の式と同様です: (($f = false) or true)
$f = false or true;

var_dump($e, $f);

// --------------------
// "&&" の優先順位は "and" より高くなります

// $g に代入されるのは、(true && false) の評価結果です
// これは、次の式と同様です: ($g = (true && false))
$g = true && false;

// $h に true を代入してから "and" 演算子を評価します
// これは、次の式と同様です: (($h = true) and false)
$h = true and false;

var_dump($g, $h);

上の例の出力は、 たとえば以下のようになります。

add a note

User Contributed Notes 21 notes

15 years ago
Note that PHP's boolean operators *always* return a boolean value... as opposed to other languages that return the value of the last evaluated expression.

For example:

$a = 0 || 'avacado';
print "A: $a\n";

will print:

A: 1

in PHP -- as opposed to printing "A: avacado" as it would in a language like Perl or JavaScript.

This means you can't use the '||' operator to set a default value:

$a = $fruit || 'apple';

instead, you have to use the '?:' operator:

$a = ($fruit ? $fruit : 'apple');
dumitru at floringabriel dot com
5 years ago
In addition to what Lawrence said about assigning a default value, one can now use the Null Coalescing Operator (PHP 7). Hence when we want to assign a default value we can write:

$a = ($fruit ?? 'apple');
//assigns the $fruit variable content to $a if the $fruit variable exists or has a value that is not NULL, or assigns the value 'apple' to $a if the $fruit variable doesn't exists or it contains the NULL value
thisleenobleNOSPAMPLEASE at mac dot com
6 years ago
In order to kind of emulate the way javascript assigns the first non-false value in an expression such as this:

var v = a || b || c || d;

I wrote a little helper method that I put in a function dump library (here presented as a bare function):

function either($a, $b){
$val = $a ? $a : $b;
             Yes, I know the fixed parameters in the function
             are redundant since I could just use func_get_args,
             but in most instances I'll be using this a replacement
             for the ternary operator and only passing two values.
             I don't want to invoke the additional process below
             unless I REALLY have to.
$args = func_get_args();
$val === false && count($args) > 2){
$args = array_slice($args, 2);

$args as $arg){
$arg !== false){
$val = $arg;

Now instead of:

$v = $a ? $a : $b;

I write:

$v = either($a, $b);

but more importantly, instead of writing:

$v = $a ? $a : ($b ? $b : $c);

I write:

$v = either($a, $b, $c);

or indeed:

$v = either($a, $b, $c, $d, $e, $f, $g, $h);
2 years ago
In response to Lawrence about || always returning a boolean:

Instead of

$x ? $x : 'fallback'

you can also use the "elvis operator":

$x ?: 'fallback'

which is useful in cases, where the left-hand side of the ternary operator is too long type, is too complex to calculate twice, or has side-effects.

It also combines nicely with the ?? operator, which is equivalent to an empty() check (both isset() and `!= false`):

$x->y ?? null ?: 'fallback';

instead of:

empty($x->y) ? $x->y : 'fallback'
pepesantillan at gmail dot com
15 years ago
worth reading for people learning about php and programming: (adding extras <?php ?> to get highlighted code)

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 "=", so

= false or true;

//is like writting

($f = false ) or true;


$e = false || true;

is the same as

$e = (false || true);


same goes for "&&" and "AND".

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.
momrom at freenet dot de
13 years ago
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().

function a($x) { echo 'Expression '; return $x; }
b($x) { echo 'is '; return $x; }
c($x) { echo $x ? 'true.' : 'false.' ;}

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':

( min( (bool) a( false ), (bool) b( true ) ) );
phpnet at zc dot webhop dot net
10 years ago
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.
15 years ago
> <?php
> 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. :/
brian at zickzickzick dot com
9 years ago
This has been mentioned before, but just in case you missed it:

// Defaults --

    //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';
peter dot kutak at NOSPAM dot gmail dot com
15 years ago
$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

($test = true) and false;

due to "&&" having a higher precedence than "=" while "and" has a lower one
anatoliy at ukhvanovy dot name
8 years ago
If you want to use the '||' operator to set a default value, like this:

= $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:

= ($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) {
$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» (, now you can code like this:

= ($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!

= '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'!
void at informance dot info
8 years ago
To assign default value in variable assignation, the simpliest solution to me is:

= 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.
martinholtcbi at gmail dot com
3 months ago
In PHP, the || operator only ever returns a boolean. For a chainable assignment operator, use the ?: "Elvis" operator.

let a = false;
let b = false;
let c = true;
let d = false;
let e = a || b || c || d;
// e === c

= 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.
samantha at adrichem dot nu
8 years ago
|= true;

does not/no longer returns a boolean (php 5.6) instead it returns int 0 or 1
4 years ago
A || B   may be different from  B || A

for exemple :

if (    ($a < 0)   ||   (!isset($a))   )
echo 'Hello!';  

//      return error:  "Notice: Undefined variable: a "

if (    (!isset($a))   ||    ($a < 0)  )
echo 'Hello!';  

//      return   'Hello!'

practical example with an age check over 17 years:
if (    (!isset($age))   ||    ($age < 17)  )
$error_age = true;

this example will not display a php error if the age is not entered
vasko at tsintsev dot com
6 years ago
Here is something useful for OR ( or any other ) bitwise comparison:

$a = 0;
$b = 1;

printf('$a = %1$04b | $b = %2$04b ...  PROCESSED is: %3$s ( %3$04b )', $a, $b, ($a | $b));
drevilkuko at gmail dot com
7 years ago
using NULL coalesce operator:

= true == false ?? 'no';
var_dump($nc); // false

$nc = null ?? 'yes';
var_dump($nc); // yes

$username = null == false ?? 'no';
var_dump($nc); // true

$nc = $_GET['something'] ?? 'default';
var_dump($nc); // default

$nc = !isset($_GET['something']) ?? 'wtf';
var_dump($nc); // true

$nc = isset($_GET['something']) ?? 'wtf';
var_dump($nc); // false

$_POST['second'] = 'chain';
$nc = $_GET['first'] ?? $_POST['second'] ?? $_REQUEST['third'] ?? 'wtf';
var_dump($nc); // chain
mcodingset at outlook dot com
4 years ago
// __forFun ...
// Example Logical `or` operator

$a = true;                  // true|false or something for test :)
$b = "I'm a string result"; // use|test `string` or `object`

if (!$a or !$c = $b) {
    $c = 'Hey';

// print result
var_dump($c); // "I'm a string result"

Have Fun!
moschris at gmail dot com
6 years ago
Unlike C++ and related languages, side effects in the left operand may NOT be used in the right operand.

e.g. if ($a=1 && $a>0)
will produce an unassigned error if $a has not previously been assigned a value.
7 years ago
Assign a value to a variable if it isn't defined


isset($x) || $x = 123;

$x; // 123


instead of:

if ( !isset($x)) {
$x = 123;

// or

$x = isset($x) ? $x : 123;

// or

$x = isset($x) ?: 123;

editor's note: In PHP 7 you could use the coalesce operator and do:
= $x ?? 123;
paranoiq at centrum dot cz
15 years ago
and, or and xor can be used as conditional constructs:

// do_that() is executed only if do_this() returns false
if($something) do_this() or do_that();
// $b is assigned to $b, do_that() is executed if $b is false
if($something) $a = $b or do_that();

// do_that() is executed only if do_this() returns true
if($something) do_this() and do_that();
// $b is assigned to $b, do_that() is executed if $b is true
if($something) $a = $b and do_that();

// both do_that() and do_this() are executed..
if($something) do_this() xor do_that();
// .. so the behaviour is same as:
if($something) {

for understanding what happens if $b is NULL or do_this() returns NULL, read the avbentem's comment on NULL type. generaly speaking, NULL is threated like false in most cases.
To Top