开发者

What's the difference between equal and identical comparison operators in PHP? [duplicate]

开发者 https://www.devze.com 2023-02-05 05:08 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: How d开发者_如何学Goo the equality (== double equals) and identity (=== triple equals) comparison operators d
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

How d开发者_如何学Goo the equality (== double equals) and identity (=== triple equals) comparison operators differ?

I know the basic difference between == and === , but can some experienced coders tell me some practical examples for both cases?


== checks if the values of the two operands are equal or not. === checks the values as well as the type of the two operands.

if("1" == 1)
   echo "true";
else
   echo "false";

The above would output true.

if("1" === 1)
   echo "true";
else
   echo "false";

The above would output false.

if("1" === (string)1)
   echo "true";
else
   echo "false";

The above would output true.


Easiest way to display it is with using strings. Two examples:

echo ("007" === "7" ? "EQUAL!" : "not equal"); 
echo ("007" == "7" ? "EQUAL!" : "not equal"); 


In addition to @DavidT.'s example, a more practical example is the following:

$foo = "Goo";
$bar = "Good Morning";
if (strpos($bar,$foo))
  echo "Won't be seen, returns false because the result is in fact 0";
if (strpos($bar,$foo) !== false)
  echo "True, though 0 is returned it IS NOT false)";
0

精彩评论

暂无评论...
验证码 换一张
取 消