views:

176

answers:

2

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?

+3  A: 

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

Tordek
+1  A: 

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.

Mike