17
I was analyzing a code in PHP and came across the following:
$result = !! $row;
return $result;
What is this !!
and what he does?
17
I was analyzing a code in PHP and came across the following:
$result = !! $row;
return $result;
What is this !!
and what he does?
17
if uses 2 !!
to convert to binary Type-safe
, or if the method or function that uses this value makes a gettype
the result will be Boolean. Not all API or lib rely on dynamic typing maybe this is the case of use.
When Converting to Boolean, the following values are considered FALSE:
the Boolean FALSE itself
the integers 0 and -0 (zero)
the floats 0.0 and -0.0 (zero)
the Empty string, and the string "0"
an array with zero Elements
the special type NULL (including unset variables)
Simplexml Objects created from Empty tags
and in the case (bool)$row
and !!$row
generate the same result bool(true|false)
.
@from: https://www.php.net/manual/en/language.types.boolean.php
11
Complementing the Jroger answer, and applying in the context of the question code, the double use of the negation operator !!
can be used to find out if an array is empty or not, as a replacement for count($array) > 0
or !(empty($array))
.
<?php
$a = !![]; // retorna false;
echo ($a ? 'array cheia' : 'array vazia'). PHP_EOL; // retorna 'array vazia'
$array = ["um", "dois", "três"];
echo (!!$array ? 'array cheia' : 'array vazia') . PHP_EOL; // retorna 'array cheia'
?>
Can also be used with string (not advisable because the string "0" gives false result to empty):
<?php
echo (!!'testing' ? 'string cheia' : 'string vazia') . PHP_EOL; // retorna 'string cheia'
echo (!!'' ? 'string cheia' : 'string vazia') . PHP_EOL; // retorna 'string vazia'
?>
Very good answer.
Browser other questions tagged php operators
You are not signed in. Login or sign up in order to post.
Converts the result to Boolean.
– rray
@rray then the
(bool)$row
and!! $row
is the same thing?– CypherPotato
It’s not easy to find more is dup.
– Maniero
Exactly, I remember there was one about C that explained this
– rray
@Maniero https://answall.com/questions/29014/qual-sentido-de-usar-dupla-nega%C3%A7%C3%a3o-en-javascript this?
– bfavaretto
@Maniero I searched the site but found nothing, so I asked. But if you have a question that already answers that, you can flag my Q as dup.
– CypherPotato
@bfavaretto I think it is.
– Maniero