Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to cast this boolean expression?

Tags:

php

In PHP 7, the following snippet strangely prints true:

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

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

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

What is the phenomenon that causes this to happen?

like image 423
Hypershadsy Avatar asked Dec 18 '22 12:12

Hypershadsy


1 Answers

It's not the cast that's doing it, it's the parentheses. and has lower precedence than =, so your first statement is treated as

($b = true) and false;

You need to write:

$b = (true and false);

or

$b = true && false;

&& and and are equivalent except for their precedence (the same goes for || and or).

like image 150
Barmar Avatar answered Jan 01 '23 21:01

Barmar