Logical Operators in php

Logical operators in php provide ways for you to build complex logical expressions. Logical operators treat their operands as Boolean values and return a Boolean value. There are both punctuation and English versions of the operators (|| and or are the same operator). The logical operators are

Logical AND (&&, and)

The result of the logical AND operation is true if and only if both operands are true; otherwise, it is false. If the value of the first operand is false, the logical AND operator knows that the resulting value must also be false, so the righthand operand is never evaluated. This process is called short-circuiting, and a common PHP idiom uses it to ensure that a piece of code is evaluated only if something is true. For example, you might connect to a database only if some flag is not false:

$result = $flag and mysql_connect();

The && and and operators differ only in their precedence

Logical OR (||, or)

The result of the logical OR operation is true if either operand is true; otherwise, the result is false. Like the logical AND operator, the logical OR operator is short circuited. If the lefthand operator is true, the result of the operator must be true, so the righthand operator is never evaluated. A common PHP idiom uses this to trigger an error condition if something goes wrong. For example

$result = fopen($filename) or exit();

The || and or operators differ only in their precedence

Logical XOR (xor)

The result of the logical XOR operation is true if either operand, but not both, is true; otherwise, it is false

Logical negation (!)

The logical negation operator returns the Boolean value true if the operand evaluates to false, and false if the operand evaluates to true.

Leave a Comment