In PHP, 0 (int, zero) is equal to “first” or “last” (strings)?

前端 未结 4 733
猫巷女王i
猫巷女王i 2021-01-21 07:43

I\'m confused by something I just ran into in a script I was working on. I had the following:

function getPart($part)
{
    $array = array(\'a\', \'b\', \'c\');         


        
相关标签:
4条回答
  • 2021-01-21 08:04

    Check out (int) 'first'. That is essentially what PHP is doing to the right hand operand.

    PHP will coerce operand types when not using the strict equality comparison operator (===) between two operands of different types.

    0 讨论(0)
  • 2021-01-21 08:07

    PHP is a bit strange in that it treats a string in numeric comparison as 0. You can force string comparison by quoting the variables:

    function getPart($part)
    {
        $array = array('a', 'b', 'c');
        if ("$part" == 'first') $part = 0;
        if ("$part" == 'last') $part = count($array) - 1;
        if (isset($array[$part])) return $array[$part];
        return false;
    }
    
    0 讨论(0)
  • 2021-01-21 08:09

    If you try to compare a string to a number, PHP will try to convert the string to a number. In this case, it fails to do so, since PHP can't convert "first" or "last" into a number, so it simply converts it to zero. This makes the check 0 == 0, which is, of course, true. Use the identity operator, ===, if you want PHP to not attempt to convert anything (so, the two operands must have the same value and be of the same type).

    0 讨论(0)
  • 2021-01-21 08:24

    PHP is weakly typed. What's happening there is it's trying to convert "first" to a number. It fails, and returns zero. It now has two numbers: zero and zero. To make it not try to convert the types, use === rather than ==.

    0 讨论(0)
提交回复
热议问题