Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

php - Type casting and Comparison with Loose Operator "=="

I have a problem baffling me terribly. I noticed this before but didn't give it any heed until today. I was trying to write my own check for integer strings. I know of is_numeric() but it does not suffice since it counts float as numeric not only integers and is_int() which does not work on string numbers.

I did something similar to this


$var1 = 'string';
$var2 = '123'; 

var_dump( (int)$var1 == $var1);// boolean true 
var_dump((int)$var2 == $var2);// boolean true

 var_dump((int)$var1);//int 0
 var_dump($var1);//string 'string' (length=6)

As expected the second var dump outputs true since I expect with php's loose comparison that the string and integer versions be equal.

However with the first, I don't get why this is so. I have tried casting to bool and it still gives me the same result.

I have tried assigning the cast var to a new variablr and comparing the two, still the same result

Is this something I am doing wrong or it is a php bug?

***Note I am not comparing types here. I'm actually trying to take advantage of the fact that int 0 is not equal to string 'string'.

I wrote my integer check differently so I don't really need alternatives for that.

***Edit I did some extra checking and it turns out that 0 == 'string' is true as well. How is that possible?

***Edit 2 There are multiple correct answers below to the question. Thanks to everyone who answered.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's not a bug, it's a feature. Any string can be casted to an integer, but the cast will return 0 if the string doesn't start with an integer value. Also, when comparing an integer and a string, the string is casted to an integer and then the check is done against the two integers. Because of that rule, about just any random string is "equal" to zero. (To bypass this behavior, you should use strcmp, as it performs an explicit string comparison by casting anything passed to a string.)

To make sure I'm dealing with an integer, I would use is_numeric first, then convert the string to an int, and verify that the stringified int corresponds to the input value.

if (is_numeric($value) && strcmp((int)$value, $value) == 0)
{
    // $value is an integer value represented as a string
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...