What does the double not operator do in PHP?
For example:
return !! $row; What would the code above do?
The double negation(!!) operator calculates the truth value of a value. This operator returns a boolean value, which depends on the truthiness of the given expression.
double exclamation exclamation marks Laravel People cast to bool by using !! It is equal to : return (bool) $value; You can interpret it in this way: It's the not !
In PHP, expressions that use logical operators evaluate to boolean values. Logical operators include: or ( || ) and ( && ) exclusive or ( xor )
The spaceship operator <=> is the latest comparison operator added in PHP 7. It is a non-associative binary operator with the same precedence as equality operators ( == , !=
It's not the "double not operator", it's the not operator applied twice. The right ! will result in a boolean, regardless of the operand. Then the left ! will negate that boolean.
This means that for any true value (numbers other than zero, non-empty strings and arrays, etc.) you will get the boolean value TRUE, and for any false value (0, 0.0, NULL, empty strings or empty arrays) you will get the boolean value FALSE.
It is functionally equivalent to a cast to boolean:
return (bool)$row;
It's the same (or almost the same - there might be some corner case) as casting to bool. If $row would cast to true, then !! $row is also true.
But if you want to achieve (bool) $row, you should probably use just that - and not some "interesting" expressions ;)
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