dth42345
dth42345
2013-01-23 17:14

转换与不同的比较

已采纳

If I have a variable which is given a string that could also be a number, as so:

$a = "1";

If I want to check if it is indeed equal to 1, is there any functional difference between

if((int)$a == 1) {
    whatever();
}

and

if($a == "1") {
    whatever();
}

Here I am thinking about PHP, but answers about other languages will be welcome.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dongtu7567 dongtu7567 8年前
    $a = "1"; // $a is a string
    $a = 1; // $a is an integer
    

    1st one

    if((int)$a == 1) {
     //int == int
        whatever();
    }
    

    2nd one

    if($a == "1") {
       //string == string
        whatever();
    }
    

    But if you do

    $a = "1"; // $a is a string
    
    if($a == 1) {
       //string & int
       //here $a will be automatically cast into int by php
        whatever();
    }
    
    点赞 评论 复制链接分享
  • duanguo7021 duanguo7021 8年前

    since your question also asks about other languages you might be looking for more general info, in which case dont forget about triple equals. which is really really equal to something.

    $a = "1";
    if ($a===1) {
      // never gonna happen
    }
    $b = 1;
    if ($b === 1) {
      // yep you're a number and you're equal to 1
    }
    
    点赞 评论 复制链接分享
  • dqspy04266 dqspy04266 8年前

    In the first case you need to convert and then compare while in the second you only compare values. In that sense the second solutions seems better as it avoids unnecessary operations. Also second version is safer as it is possible that $a can not be casted to int.

    点赞 评论 复制链接分享