comparing two variables returns false result

后端 未结 5 1069
感情败类
感情败类 2021-01-25 13:27

Why does this always return true:

$s = \'334rr\';
$i = (int)$s;

if ($i == $s) {
    echo true;
} else {
    echo false;
}

If I ec

相关标签:
5条回答
  • 2021-01-25 13:51

    From the manual:

    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.

    So: ($i == $s) is the same as ($i == (int)$s) for the values you've given.

    Use === to avoid type-juggling.

    0 讨论(0)
  • 2021-01-25 13:56

    Comparing strings to an int is not recommended. You should use the === instead which will verify the same data type as well as the same value.

    0 讨论(0)
  • 2021-01-25 14:01

    PHP converts the $s string to an integer when comparing to another integer ($i). It basically does this (well, i don't know what it does internally, but it boils down to this):

    if($i == (int) $s)
    

    Which makes the statement true

    0 讨论(0)
  • 2021-01-25 14:06

    When compare string with integer using ==, string will try to case into integer.

    0 讨论(0)
  • 2021-01-25 14:10

    Try this

    $s = '334rr';
    $i = intval($s);
    if ($i == $s) {
     echo true;
     } else {
      echo false;
    }
    
    0 讨论(0)
提交回复
热议问题