在IF条件下与int和string比较

Mon*_*nty 5 php string casting compare type-conversion

PHP代码:

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

要么

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

输出:Mackraja

Ben*_*Ben 9

如果将数字与字符串进行比较或比较涉及数字字符串,则每个字符串将转换为数字,并且数字执行比较.这些规则也适用于switch语句.- 来源

这意味着

<?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
Run Code Online (Sandbox Code Playgroud)

因此,当您将$key(与值0)与字符串进行比较时,字符串具有值,0并且它们都返回true.这样,它将始终输出"Mackraja".

将值更改$key为任何其他整数将返回false.


注意

比较时不会发生类型转换,===或者!==这涉及比较类型和值.- 来源

这意味着改变比较运算符来===将意味着值必须匹配完全-即一个字符串,1等于整数1:他们必须匹配的格式:

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

echo $key === 'monty' && $key === 'anil' ? 'Mackraja' : 'Nothing';
//will echo "Nothing"
Run Code Online (Sandbox Code Playgroud)


Mon*_*nty 1

经过与同事长时间的讨论: 我们找到了解决方案

例子 :

#1    var_dump("00005ab" == 5); // true
#2    var_dump("abc" == 0); // true
#3    var_dump(2 == "ab2"); // false
#4    var_dump(2 == "2ab"); // true
Run Code Online (Sandbox Code Playgroud)

解释 :

在条件左操作数 (2) 与右操作数 (ab2) 匹配的情况下,如果在开头没有找到,则输出将为 false,否则为 true。

#1 : we found 5 at the begining output will be true. 0 will be eliminated.
#2 : string + int = int output will be true. 
     Priority of int is higher, 0 == 0 output will be true,
#3 : 2 is not found at the beginning of match value (ab2), output will be false.
#4 : 2 is found at the beginning of match value (2ab), output will be true.
Run Code Online (Sandbox Code Playgroud)

原因 :

1.) In PHP, its automatically convert Type Casting.
2.) Rules of Type Casting : 
    2.1) int + int = int
    2.2) string + string = string
    2.3) float + float = double
    2.4) int + string = int     
    2.5) float + string = double
    2.6) int + float = double
Run Code Online (Sandbox Code Playgroud)