开发者

why does this evaluate to true

Whey does this evaluate to true?

<?php


$val2=0;

//outputs that is an error123
if($val2=='error123'){
   echo 'that is an error123<br />';
}else{
   echo 'that 开发者_运维问答is not an error123<br />';
}  


You're comparing a string to an integer. To make the comparison the string is first converted to an integer. When 'error123' is converted to an integer it becomes 0.

echo intval("error123");

Result:

0

In the PHP manual there is an explanation for this behaviour.

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

There is a quick reference page PHP type comparison tables that shows you the result of various comparions. See the table "Loose comparisons with ==". The interesting part with regard to this question is that 0 == "php" is shown as TRUE.

There is also a page on type juggling. A user comment on that page gives nearly the exact same example as this.

If you don't want the type juggling use === instead of ==.


Give this a try: $val2==='error123'

That will evaluate the value and the type of the variable. More here:

http://us.php.net/manual/en/language.operators.comparison.php

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜