1
$vartest = 0;

if ($vartest == "This can't be TRUE")  { echo "But it is TRUE"; }

>> But it is TRUE

By mistake I made a wrong declaration somewhere in my program, and discovered this strange behaviour.

I used $vartest = “” most of the time, but somewhere $vartest = 0 slipped into the program.

Because I spent hours to find the error I’m posting this just for awareness.

Just one question. The variable $vartest is empty, but why does PHP find this TRUE ?

Eduard
  • 25
  • 4
  • Check [this](http://stackoverflow.com/questions/6843030/why-does-php-consider-0-to-be-equal-to-a-string) – Stuti Rastogi May 12 '17 at 12:33
  • try `echo (int) "This can't be true";` and you'll see that when you cast that string to an int it **is** 0; therefore; since you initially declared `$vartest` to be an int, that's what's happening. – CD001 May 12 '17 at 12:34
  • You should use === instead of ==, because the ordinary operator does not compare the types will typecast the items. But the === takes in consideration type of items. – JYoThI May 12 '17 at 12:35

1 Answers1

-1

You had to compare on equality and type with "===" and not only with "==" for equality with typeconversion. Try this:

$vartest = 0;

if ($vartest === "This can't be TRUE")  { echo "But it is TRUE"; }
Sascha
  • 4,576
  • 3
  • 13
  • 34