PHP Tutorial Tutorials - PHP Logical Operators

PHP Logical Operators

Logical Operator is also called Relational Operator.
They are typically used to combine conditional statements.

Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $$x or $y is true
! Not !$x True if $x is not true
<?php
$a = TRUE;
$b = FALSE;
function myPrint($value1,$value2,$valueRes,$operator) {
    $format = '%1$s %4$s %2$s=%3$s';
    $value1 = $value1 ? 'true' : 'false';
    $value2 = $value2 ? 'true' : 'false';
    $valueRes = $valueRes ? 'true' : 'false';
    printf($format,$value1,$value2,$valueRes,$operator);
}

myPrint($a,$a,$a and $a,'and');
echo " , ";
myPrint($a,$b,$a and $b,'and');
echo " , ";
myPrint($b,$a,$b and $a,'and');
echo " , ";
myPrint($b,$b,$b and $b,'and');
echo "<br>";

myPrint($a,$a,$a or $a,'or');
echo " , ";
myPrint($a,$b,$a or $b,'or');
echo " , ";
myPrint($b,$a,$b or $a,'or');
echo " , ";
myPrint($b,$b,$b or $b,'or');
echo "<br>";

myPrint($a,$a,$a xor $a,'xor');
echo " , ";
myPrint($a,$b,$a xor $b,'xor');
echo " , ";
myPrint($b,$a,$b xor $a,'xor');
echo " , ";
myPrint($b,$b,$b xor $b,'xor');
echo "<br>";

myPrint($a,$a,$a && $a,'&&');
echo " , ";
myPrint($a,$b,$a && $b,'&&');
echo " , ";
myPrint($b,$a,$b && $a,'&&');
echo " , ";
myPrint($b,$b,$b && $b,'&&');
echo "<br>";

myPrint($a,$a,$a || $a,'||');
echo " , ";
myPrint($a,$b,$a || $b,'||');
echo " , ";
myPrint($b,$a,$b || $a,'||');
echo " , ";
myPrint($b,$b,$b || $b,'||');
echo "<br>";
?>

The difference between "and" and "&&" is the operator precedence.

  • "&&" has a greater precedence than "and"
  • "||" has a greater precedence than "or"
<?php
$a = true && false;
$b = true and false;

var_dump($a); // bool(false) Acts like: $g = (true && false)
var_dump($b); // bool(true) Acts like: ($h = true) and false

$c = false || true;
$d = false or true;
var_dump($c); // bool(true) Acts like: $c = (false || true)
var_dump($d); // bool(false) Acts like: ($d = false) or true
?>
Date:2019-10-01 01:55:02 From:www.Lautturi.com author:Lautturi