Les opérateurs logiques

Les opérateurs logiques
Exemple Nom Résultat
$a and $b And (Et) TRUE si $a ET $b valent TRUE.
$a or $b Or (Ou) TRUE si $a OU $b valent TRUE.
$a xor $b XOR TRUE si $a OU $b est TRUE, mais pas les deux en même temps.
! $a Not (Non) TRUE si $a n'est pas TRUE.
$a && $b And (Et) TRUE si $a ET $b sont TRUE.
$a || $b Or (Ou) TRUE si $a OU $b est TRUE.

La raison pour laquelle il existe deux types de "ET" et de "OU" est qu'ils ont des priorités différentes. Voir le paragraphe précédence d'opérateurs.

Exemple #1 Illustration des opérateurs logiques


// --------------------
// foo() ne sera jamais appelée car ces opérateurs s'annulent

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

// --------------------
// "||" a un précédence supérieure à "or"

// Le résultat de l'expression (false || true) est affecté à $e
// Agit comme : ($e = (false || true))
$e false || true;

// La constante false est affectée à $f, puis, true est ignoré
// Agit comme : (($f = false) or true)
$f false or true;


// --------------------
// "&&" a un précédence supérieure à "and"

// Le résultat de l'expression (true && false) est affecté à $g
// Agit comme : ($g = (true && false))
$g true && false;

// La constante true est affectée à $h, puis, false est ignoré
// Agit comme : (($h = true) and false)
$h true and false;


L'exemple ci-dessus va afficher quelque chose de similaire à :

add a note add a note

User Contributed Notes 10 notes

6 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');
phpnet at zc dot webhop dot net
1 year 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.
pepesantillan at gmail dot com
6 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
4 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 ) ) );
peter dot kutak at NOSPAM dot gmail dot com
6 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
brian at zickzickzick dot com
8 months 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';
6 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. :/
void at informance dot info
1 day 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.
dartello at gmail dot com
1 year ago
Unlike in C/C++ the invertor (Not) in PHP assumes a string:

= 1;

$t = !$a;

The above example will output:
 string(0) => ""

To approach the C/C++ handling, this can be solved as follows:

= 1;

$t = !$a;

$u = !a;

The above example will output:
paranoiq at centrum dot cz
6 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