3

I've recently had a bug that was perplexing me.... traced it down to the following (simplified) statmement, which provides a real example

function test_it($team)
{  echo (($team=="a") ? "Yep it is!" : "No Way");
}

So, if I execute test_it(0); I get the result "Yep it is!" ??

The logic of the statement looks fine, but obviously to get a correct outcome I needed to make it "==="....

Can anyone explain why this is the case? Just to help me understand why/what I should avoid in future.

Tony Carbone
  • 484
  • 4
  • 10
  • Triple equals === is the "And this time I mean it" operator. Use four equals if you really want to be sure. Five equals is just over the top. – billpg Jun 27 '13 at 09:03

5 Answers5

3

Its because of the string / char of a i.e "a" and passing through 0 .

the === operator performs a 'typesafe comparison'

Explanation and question here

Community
  • 1
  • 1
Pogrindis
  • 7,755
  • 5
  • 31
  • 44
2

It's because type juggling will make your "a" into an integer for the comparison. So in effect this is what's running:

if (0 == (int)"a") 

And of course (int)"a" will evaluate to 0, you can read more about type juggling here.

complex857
  • 20,425
  • 6
  • 51
  • 54
0

Check this link.

With == you perform loose comparison. According to the table in link, this type of comparison between 0 (an integer) and "something" (a string) will result in TRUE.

maialithar
  • 3,065
  • 5
  • 27
  • 44
0

In PHP, any string not beginning with numeric values is == to 0. For example, here's a sample with various comparisons, and the resulting echo:

$team = 0;
echo (($team=="a") ? "Yep it is!" : "No Way");    // Yep it is!
echo (($team=="abc") ? "Yep it is!" : "No Way");  // Yep it is!
echo (($team=="a really long string") ? "Yep it is!" : "No Way");  // Yep it is!

Apparently, it's not actually a bug, read more about it here > https://bugs.php.net/bug.php?id=44999.

BenM
  • 52,573
  • 26
  • 113
  • 168
0

The == operator just checks to see if the left and right values are equal. But, the === operator (note the extra “=”) actually checks to see if the left and right values are equal, and also checks to see if they are of the same variable type (like whether they are both booleans, ints, etc.)

Now do a echo (int)"a"; you will get a 0 an it's valid for any string.

Imane Fateh
  • 2,418
  • 3
  • 19
  • 23