Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP converting to boolean using '!!'

Tags:

php

boolean

Fairly straight-forward question here. Been looking over some code and I've seen a function that seems to convert a given variable to a boolean. It goes like this:

function to_bool( $var ) {
    return !!$var;
}

Pretty simple, but how does it work? Never seen this before, and googling hasn't really gotten me anywhere. Does the extra '!' sort-of flip the result? '!$var' can be used to check if a var is false, so does '!!' turn a 'false' to true, and vice versa?

like image 235
Matthew Ruddy Avatar asked Oct 03 '12 23:10

Matthew Ruddy


1 Answers

how does it work?

The not operator places the variable into a conditional. Therefore, the result is boolean. The second not flips its value.

It's more clear just to use an explicit cast in your code rather than such a function:

(bool)$var;
like image 192
webbiedave Avatar answered Sep 23 '22 19:09

webbiedave