开发者

Why the value being equalled to string in php

开发者 https://www.devze.com 2023-02-16 15:02 出处:网络
It is in this way: $arr_val = array(0,1,\'0\',\'1\'); foreach ($arr_val as $key){ echo ($key == \"TEST\")?\"EQUALLED\":\"NOT EQUALLED\".\"<br>\";

It is in this way:

$arr_val = array(0,1,'0','1');
foreach ($arr_val as $key){
    echo ($key == "TEST")?"EQUALLED":"NOT EQUALLED"."<br>";
}
  1. 0 == "TEST" prints "EQUALLED"
  2. 1 == "TEST" prints "开发者_如何学GoNOT EQUALLED"
  3. '0' =="TEST" prints "NOT EQUALLED"
  4. '1' =="TEST" prints "NOT EQUALLED"

When I say it prints the value "SELECTED". But why the above first case prints equalled. Any ideas on this please? How would this be equal to. We know the fix to do comparision with (===) operator. But I am trying to know the reason why (0=="TEST") is true.


When you provide PHP's == operator with a mixture of numeric and string operands, PHP will attempt to convert the string to the matching numeric type, part of a process it calls "type juggling". In this case, the string "TEST" converts to integer 0 so your test is equivalent to 0 == 0 which is true.

PHP provides the === operator, for testing if the value and type of both operands are equal. So while 0 == "TEST" will evaulate to true, 0 === "TEST" will not, and neither will 0 === "0" or 0 === 0.0.

Note that when PHP converts a string to a number, it attempts to parse the string for a valid number. See intval for more information on how it does this. Had you'd written 0 == "1TEST", the expression would have evaulated to 0 == 1, or false.

In your second example, 1 == "TEST", the string "TEST" is again converted to an integer resulting in 1 == 0, which is false.

Your last two examples use string comparisons. There is no conversion involved, and the results are self-explanatory.

PHP provides a comprehensive breakdown of how variables of different type compare for equality.


Because 0 is an integer, behind the scenes, this is the comparison that happens:

0 == intval( "TEST" )
0

精彩评论

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

关注公众号