Tutorials PHP Comparison with == and ===

Comparison with == and ===

Today's lesson will be on the difference between multiple equal signs in your comparisons. One equal sign is assignment, two is content comparison, three is content and type comparison.

Whats the difference between two equal signs and three?

Let's do a simple test to find out.

$string  = '123';
$integer = 123;

// Two equal signs comparison
// Answer is that it does match
if ($string == $integer) {
  echo 'Two equal signs match.';
} else {
  echo 'Two equal signs do not match.';
}

// Three equal signs comparison
// Answer is that it does not match
if ($string === $integer) {
  echo 'Three equal signs match.';
} else {
  echo 'Three equal signs do not match.';
}

The numbers are both the same on this test, but the first test passes while the second test doesn't. The names give it away, but the one in quotes in a string while the one without quotes is an integer. The test with two quotes just checks the content so since they are both the same number, it passes. The test with three quotes checks for content and type and since one is a string and one is an integer, it fails the test. Three equal signs are more strict; if three equal signs match, two will always match.

That's all for today's lesson. Hopefully you can integrate the different comparisons into your scripts to patch up any security loopholes while also having enough leeway to prevent fatal errors on users.

Posted by on . Category: PHP


Comments

No comments posted yet

You need to register or login to post new comments.