Search code examples
phpcomparisonoperatorscomparison-operators

Difference between "!==" and "==!"


Yesterday I stumbled over this when I modified PHP code written by someone else. I was baffled that a simple comparison (if ($var ==! " ")) didn't work as expected. After some testing I realized that whoever wrote that code used ==! instead of !== as comparison operator. I've never seen ==! in any language so I wondered how the hell this code could even work and did some testing:

<?php
echo "int\n";
echo "1 !== 0: "; var_dump(1 !== 0);
echo "1 !== 1: "; var_dump(1 !== 1);
echo "1 ==! 0: "; var_dump(1 ==! 0);
echo "1 ==! 1: "; var_dump(1 ==! 1);
echo "bool\n";
echo "true !== false: "; var_dump(true !== false);
echo "true !== true: "; var_dump(true !== true);
echo "true ==! false: "; var_dump(true ==! false);
echo "true ==! true: "; var_dump(true ==! true);
echo "string\n";
echo '"a" !== " ": '; var_dump("a" !== " ");
echo '"a" !== "a": '; var_dump("a" !== "a");
echo '"a" ==! " ": '; var_dump("a" ==! " ");
echo '"a" ==! "a": '; var_dump("a" ==! "a");
?>

This produces this output:

int
1 !== 0: bool(true)
1 !== 1: bool(false)
1 ==! 0: bool(true)
1 ==! 1: bool(false)
bool
true !== false: bool(true)
true !== true: bool(false)
true ==! false: bool(true)
true ==! true: bool(false)
string
"a" !== " ": bool(true)
"a" !== "a": bool(false)
"a" ==! " ": bool(false)
"a" ==! "a": bool(false)

The operator seems to work for boolean and integer variables, but not for strings. I can't find ==! in the PHP documentation or anything about it on any search engine (tried Google, Bing, DuckDuckGo, but I suspect they try to interpret it instead of searching for the literal string). Has anybody seen this before and can shed any light on this behavior?


Solution

  • The difference is that there is no operator ==!.

    This expression:

    $a ==! $b
    

    Is basically the same as this:

    $a == (!$b)