DEV Community

david duymelinck
david duymelinck

Posted on

PHP: Stop using the identical comparison operator everywhere

This is more a note to self post. But I thought maybe it is beneficial for others as well.

The identical comparison operator or three equal signs, is so deep in my muscle memory and vision that for a long time I didn't even notice typing that third equal sign, or bat an eye when it is there.

But these last weeks I'm becoming more and more aware of the uselessness of the type check that is build-in the identical comparison operator.

In the good old days I would write something like

function isEqual($a, $b) 
{
    return $a === $b;
}
Enter fullscreen mode Exit fullscreen mode

But I'm using type hinting more and more. So that code gets rewritten as

function isEqual(string $a, string $b)
{
   return $a == $b;
}
Enter fullscreen mode Exit fullscreen mode

The type check has moved to the arguments.

And even with functions that have multiple return types, it makes no sense anymore. Even the official documentation has examples like this, for instance the strpos function.

$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
// do something
}
Enter fullscreen mode Exit fullscreen mode

The check could be replaced by is_bool($pos).

Now that I'm aware of this ingrained behavior, I'm discovering a lot of places where I have why-did-i-do-that moments.

The identical comparison operator is not obsolete, but start questioning the usage in the code.

Top comments (3)

Collapse
 
humbertocandido profile image
Humberto Francisco da Silva Candido

Thanks for the tip, very insightful!

Collapse
 
jdrab profile image
Ján Dráb

PHP variables are mutable by default, nothing will stops you from modifying a variable defined as a string (in function argument) and changing the type a few lines above the weak comparison. I know in a 3 line function it’s obvious but do we write 3 line functions?

Collapse
 
xwero profile image
david duymelinck

You are right that a variable can change type, I find myself more conscious of types by doing type hinting.

Also the cases that the argument type changes are rare. When the type changes most of the times I use a new variable because the argument is transformed.

function isEqual(string $a, string $b)
{
  $aDate = new DateTime($a);
  $bDate = new DateTime($b);

   return $aDate == $bDate;
}
Enter fullscreen mode Exit fullscreen mode

In the examples I used bad naming, but If good names are used in combination with type hinting the risk of accidental type changes will be minimal.
I think the identical comparison operator should only be used in cases when it is highly likely one of the variables is of a different type, and it is not possible to type cast.