Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double not (!!) operator in PHP

Tags:

operators

php

What does the double not operator do in PHP?

For example:

return !! $row; 

What would the code above do?

like image 842
Andrei Avatar asked Jan 24 '10 13:01

Andrei


People also ask

What is double Not operator?

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.

What is double exclamation mark in PHP?

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 !

What is mean by || and && in PHP?

In PHP, expressions that use logical operators evaluate to boolean values. Logical operators include: or ( || ) and ( && ) exclusive or ( xor )

What does <> mean in PHP?

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 ( == , !=


2 Answers

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; 
like image 156
Theo Avatar answered Sep 18 '22 19:09

Theo


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 ;)

like image 27
viraptor Avatar answered Sep 21 '22 19:09

viraptor