在PHP中,0(int,零)等于"first".或“最后" (弦)? [英] In PHP, 0 (int, zero) is equal to "first" or "last" (strings)?

查看:154
本文介绍了在PHP中,0(int,零)等于"first".或“最后" (弦)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对自己正在使用的脚本中遇到的某些事情感到困惑.我有以下内容:

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');
    if ($part == 'first') $part = 0;
    if ($part == 'last') $part = count($array) - 1;
    if (isset($array[$part])) return $array[$part];
    return false;
}

$position = 0;
echo getPart($position);

因此,如果我尝试使用字符串"first",则应该获得"a"作为输出.使用字符串"last",我应该得到"c",依此类推.当我使用PHP 5.3运行上述脚本时,出现"c" ...

So, if I were to try the string "first", I should get "a" as the output. With the string "last" I should get "c" and so on. When I run the script above, with PHP 5.3, I get "c" ...

困惑,我进行了快速测试...

Confused, I ran a quick test ...

var_dump(0 == 'first');
var_dump(0 == 'last');

两者都返回TRUE ... 为什么?我对此行为感到困惑!

Both return TRUE ... WHY??? I am so confused by this behavior!

推荐答案

如果您尝试将字符串与数字进行比较,PHP将尝试将字符串转换为数字.在这种情况下,它无法执行此操作,因为PHP无法将"first" "last" 转换为数字,因此只能将其转换为零.这使得检查0 == 0当然是正确的.如果希望PHP不尝试转换任何内容,请使用标识运算符===(因此,两个操作数必须具有相同的值并且具有相同的类型).

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).

这篇关于在PHP中,0(int,零)等于"first".或“最后" (弦)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆