Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Why typecast with !!$var instead of (boolean)$var?

Both of these will ensure than $var is a boolean value, but the latter seems more clear. The double exclamation mark (!!) is shorter to type but less clear, and more likely to cause confusion. Not to mention hard to run a search on to get answers.

The double exclamation mark is something I've only heard of in JavaScript, which doesn't have boolean typecasting. Is it normal to see it used in PHP as well?

like image 514
David Calhoun Avatar asked Jan 01 '10 06:01

David Calhoun


2 Answers

This is valid in JavaScript, although not technically a "cast", it achieves the same effect:

var booleanValue = Boolean(otherValueType);

This is equivalent to:

var booleanValue = !!otherValueType;

I find it is good to do this when processing incoming parameters, to clarify that one intended a value to be a boolean. When checking for "truthiness", there is no need to typecast in either PHP or JavaScript. Just remember that an empty string is equivalent to false in PHP and true in JavaScript.

So, to answer your question, either is fine in either language, it is simply a personal style choice.

like image 126
Mike Avatar answered Sep 23 '22 20:09

Mike


Neither of those is common in PHP because they're unnecessary.

If you can do !!, you can just as well use it where a boolean expression is necessary (while, if, &&, etc.).

like image 24
Tordek Avatar answered Sep 22 '22 20:09

Tordek