Search code examples
phpbooleanalgebra

Learning PHP, Boolean algebra


So i've just started learning PHP and i came across a part i didn't quite understand.

The book gave me three lines.

&& and true && true=true, every other combination results in false.

|| or false || false=false, every other combination results in true.

XOR or false XOR true=true, every other combination results in false.

If anyone can clarify what this means i would very much appreciate it.

Edit

the following is text above my previous part.

Every equation yields a value: either true(1) or false(0).

echo true + true + false

This results in a value of 2 (1 + 1 + 0).


Solution

  • There are three boolean operators mentioned there: && (logical AND), || (logical OR), and XOR (well, it's logical XOR, or 'exclusive OR'). All of these are binary ones - they take two operands. Its result, apparently, is a boolean value - either true or false.

    Now, they function as follows:

    • && will only result in true if both its operands evaluate to true, otherwise the result will be false
    • || will only result in false if both its operands evaluate to false, otherwise the result will be true
    • XOR will result in false if its operands evaluate to the same value - be it true or false, doesn't matter. But if one operand evaluates to false, and another to true, the result is true.

    Now, on the second part of your question: this...

    echo true + true + false;
    

    ... doesn't have anything to do with boolean algebra. All the operands of + are cast to the numeric type first, by the rules described in Type Juggling section of the PHP documentation. In short, true is converted to 1, false to 0; the result - 1 + 1 + 0, or 2, is printed out.