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

前端 未结 4 732
猫巷女王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: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;
    }
    

提交回复
热议问题