Logical operators are pretty simple if you’ve taken Boolean Algebra or are familiar with logic-gates. You might have even been exposed to logic in Philosophy. If you’re not familiar with logic, this may be a bit of a shock for you. Only joking. It’s just another operator in our disposal that evaluates to either true or false.

We looked at how to test whether an expression is true or not, but how can we test whether multiple expressions are true? With logical operators, that’s how.

There are a few operators in PHP that test the truth value of two expressions.

  • AND: returns true only if both the left and the right expressions evaluate to true.
  • &&: same as AND but with different precedence.
  • ||: returns true if either the left or the right, or both, expressions evaluate to true.
  • OR: same as || but with different precedence.
  • XOR: returns true only if either the left or the right expressions are true, but not both.
  • !: Negation. Returns true if false, and false if true.
<?php

var_dump( true && true ); // evaluates to true
$a = "lowered";
$b = "boosted";
var_dump($a == "lowered" AND $b == "boosted"); // true
?>

In the example above, with the expression true AND true, we have true on the left and true on the right sides. True AND True evaluates to true.

In the second example, we evaluate the expression on the left and the expression on the right. The expression on the left, $a == “lowered”, evaluates to true since $a does contain the string “lowered.” The expression on the right also evaluates to true since $b does contain the string “boosted.” Since both sides return true, we get true AND true. In order for the AND operator to return true, both the left and the right expressions have to evaluate to true. Since they do, it returns true.

We can use the negation operator to obtain the opposite value of the expression.

<?php

$a = "codeigniter";
$b = "laravel";
var_dump( $a == "codeigniter" && $b != "zend" ); // true
var_dump( !true ); // false
var_dump( !false ); // true
?>

#php #programming #software-development #web-development #logical

PHP 7.x — P19: Logical Operators
1.25 GEEK