1

I wanted to check two strings with each other, one which starts with a zero and one without. But this seems to result in a true. An example:

if("098" == "98"){
   return true;
}

Can somebody explain why this statement results to true with PHP?

Nuri Ensing
  • 1,899
  • 1
  • 19
  • 42

2 Answers2

1

The simple reason i can think of is that The operator == casts between two different types if they are different, while the === operator performs a 'typesafe comparison'. That means that it will only return true if both operands have the same type and the same value.

So from your example,

if("098" == "98"){
   //true
}

Also a couple of PHP functions also have parameters to imply strict checking. An example is in_array

Rotimi
  • 4,783
  • 4
  • 18
  • 27
1

if you compare with ==, php tries to compare them without respecting the type. So what actually happens, php converts the two numbers to an integer, and as 98 is equal to 98, "098" == "98" is also true.

The best way to avoid this is, use ===, which compares also the type without any conversions.

if("098" === "98"){
    return true;
}
Philipp
  • 15,377
  • 4
  • 35
  • 52