Frage

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).

War es hilfreich?

Lösung

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.

Andere Tipps

It is referring to the fact that and and && etc. have different operator precedence.

Namely, and or or function differently than && and || with assignment statements:

$f = false or true;

Also, the operators are short-circuit operators, so if you have something that evaluates to false as the first operand with either and or && then the entire expression will immediately evaluate to false without evaluating any other operands.

http://www.php.net/manual/en/language.operators.logical.php

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top