Hi guys, does anybody know what the double not operator does in PHP
ex: return !! $row;
What would the code above do?
Thanks
Hi guys, does anybody know what the double not operator does in PHP
ex: return !! $row;
What would the code above do?
Thanks
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 ;)
Its means if $row
has a value, it will return true
otherwise false
, converting to boolean value.
Sounds like it's an abbreviation of (which in term could be made a ternary operator)
if ($value) { // if 'truthy'
return true;
} else {
return false;
}
It's a more semanticly correct value to be returned in some circumstances.
It would be much easier to use (bool)
. I wouldn't recommend using the !!
prefix, as it may confuse a future developer for a while. They'll probably come across this page via Google.
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 right ! 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
.