Reputation: 925
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?
Upvotes: 6
Views: 3869
Reputation: 2470
You can also look at this from the perspective of type conversion. In PHP, performing a logical expression on a value will give a boolean result. So, the first negation implicitly casts the value as a bool, and the second-evaluated is just to reverse the negation of the first one. You can do the same thing using other logical operators (although I wouldn't recommend it, as some have different precedence):
// using "truthy" 2 as a value //
!!2 // true
2 || false // true
2 && true // true
2 xor false // true
// using "falsey" 0 as a value //
!!0 // false
0 || false // false
0 && true // false
0 xor false // false
Upvotes: 0
Reputation: 10995
Take !!2
!2
evaluates to !(true)
which evaluates to !false
end result true
. The not boolean basically treats the right operand as a bool.
Upvotes: 3
Reputation: 10302
Hmmm... interesting.
Well, PHP follows a specific set of rules when determining whether a variable is "true" or "false".
Using certain operators will force that decision to be made. For example, when you add a string "a"
and an integer 2
with the .
operator, you'd get "a2"
, because the .
operator's intent is to concatenate.
Here, the first !
means you're attempting to negate the variable. To negate anything means that you must first be treating it as a boolean, so that's what it does. Then the second !
just negates it back.
It's a weird way of doing it. Frankly, if ($var)
would yield the same result as your if (to_bool($var))
.
Upvotes: 2
Reputation: 48897
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;
Upvotes: 10
Reputation: 13694
One !
would be an inverted boolean so two !!
make a non-inverted boolean. It's a double negation of a variable and returned as a boolean type
Upvotes: 3