php - 在 IF 条件下与 int 和 string 进行比较

标签 php string casting compare type-conversion

PHP 代码:

<?php
    $key = 0;
    if($key == 'monty' && $key == 'anil'){
        echo 'Mackraja';
    }else{
        echo "Nothing";
    }
?>

<?php
    $key = 2;
    if($key == '2abc' || $key == 'abc2'){
        echo 'Mackraja';
    }else{
        echo "Nothing";
    }
?>

输出:Mackraja

最佳答案

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. These rules also apply to the switch statement. - Source

这意味着

<?php
    var_dump(0 == "a"); // 0 == 0 -> true
    var_dump("1" == "01"); // 1 == 1 -> true
    var_dump("10" == "1e1"); // 10 == 10 -> true
    var_dump(100 == "1e2"); // 100 == 100 -> true

因此,当您比较 $key 时(值为 0 )到字符串,字符串的值为 0并且它们都返回 true。这样,它将始终输出“Mackraja”。

更改 $key 的值任何其他整数将返回 false。


注意

The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value. - Source

这意味着将比较运算符更改为 ===将意味着值必须完全匹配 - 即字符串 1等于整数 1:它们必须匹配格式:

echo $key == 'monty' && $key == 'anil' ? 'Mackraja' : 'Nothing';
//will echo "Mackraja"

echo $key === 'monty' && $key === 'anil' ? 'Mackraja' : 'Nothing';
//will echo "Nothing"

关于php - 在 IF 条件下与 int 和 string 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35173422/

相关文章:

c - 在字符串中使用下划线

如果 PHP 包含整数,则替换整个字符串

java - 为什么字符串转换循环似乎有静态开销?

php - 添加类以在 Symfony FormBuilder 中选择选项

php - 如何删除所有 session 信息?

c# - 查找单词的正则表达式

c# - 将 T[] 转换为 IList<T> 有什么注意事项吗?

java - 在 OSX 上的 Java 中从大的 long 转换为 float 时出现错误?

php - 通过 cURL 访问 import.io API 时无法获取 JSON 结果中的实际 html

php - $_SERVER ['REQUEST_URI' ] 返回完整的 URL 而不是脚本路径