Logical tricks in PHP

Do you know, how 'and' and 'or' operators works?
Probably yes. (And probably you know, what is the difference between 'and' and '&&')

What's tricky here?

The trick is: 'and' returns true when both operands are true. If the first operand is false, operator returns false immediately.
So, we can use it instead of 'if':

$flag = false;
$flag and echo "It's true.";

it works. Really.

Absolutely the same with 'or': it returns true immediately if the first operand is true (so second will not be calculated)

$flag = true;
$flag or echo "man, it's false";

I bet everyone seen the following code:

mysql_connect( 'host', 'user', 'password') or die('Could not connect to server.' );

When I first seen this I was thinking - what an interesting language, this looks like simple English...
Now I know what's the trick. And you too.

Leave a Reply