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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With