Why do I need this boolean expression?

In PHP 7, the following snippet weirdly prints true:

$b = true and false;
var_dump($b);

However, if I drop it, it prints correctly false:

$b = (bool)(true and false);
var_dump($b);

What phenomenon causes this?

+4
source share
2 answers

This is not what it does, it is parentheses. andhas a lower priority than =, therefore your first statement is considered as

($b = true) and false;

You need to write:

$b = (true and false);

or

$b = true && false;

&&and andequivalent, with the exception of their priority (the same applies to ||and or).

+7
source

This is not casting, but parentheses:

$b = (true and false);
var_dump($b);
# => bool(false)

This is due to the fact that it binds more strongly than or . =andor

:

$b = true && false;
var_dump($b);
# => bool(false)

&& || , =.

+4

Source: https://habr.com/ru/post/1660460/


All Articles