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?
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?
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
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;
}