PHP的变量类型宽大处理 [英] PHP's variable type leniency

查看:74
本文介绍了PHP的变量类型宽大处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关PHP in_array()帮助页面的最新评论( http://uk.php.net/manual/zh/function.in-array.php#106319 )指出,由于PHP的宽大处理变量类型",导致出现了一些异常结果,但未给出任何结果解释为什么会出现这些结果.特别是,我不明白为什么会这样:

The most recent comment on PHP's in_array() help page (http://uk.php.net/manual/en/function.in-array.php#106319) states that some unusual results occur as a result of PHP's 'leniency on variable types', but gives no explanation as to why these results occur. In particular, I don't follow why these happen:

// Example array

$array = array(
    'egg' => true,
    'cheese' => false,
    'hair' => 765,
    'goblins' => null,
    'ogres' => 'no ogres allowed in this array'
);

// Loose checking (this is the default, i.e. 3rd argument is false), return values are in comments
in_array(763, $array); // true
in_array('hhh', $array); // true

或者为什么张贴者认为以下是奇怪的行为

Or why the poster thought the following was strange behaviour

in_array('egg', $array); // true
in_array(array(), $array); // true

(肯定在数组中出现了"egg",PHP不在乎它是键还是值,并且有数组,PHP不在乎是否为空?)

(surely 'egg' does occur in the array, and PHP doesn't care whether it's a key or value, and there is an array, and PHP doesn't care if it's empty or not?)

任何人都可以指点一下吗?

Can anyone give any pointers?

推荐答案

在内部,您可以想到基本的in_array()调用是这样的:

Internally, you can think of the basic in_array() call working like this:

function in_array($needle, $haystack, $strict = FALSE) {
    foreach ($haystack as $key => $value) {
        if ($strict === FALSE) {
            if ($value == $needle) {
                return($key);
            }
        } else {
            if ($value === $needle) {
                return($key);
        }
    }
    return(FALSE);
}

请注意,它使用的是==比较运算符-此运算符允许进行类型转换.因此,如果您的数组包含一个简单的布尔值TRUE,那么基本上可以找到所有使用in_array搜索的内容,并且几乎可以将PHP中除以下内容之外的所有内容都转换为true:

note that it's using the == comparison operator - this one allows typecasting. So if your array contains a simple boolean TRUE value, then essentially EVERYTHING your search for with in_array will be found, and almost everything EXCEPT the following in PHP can be typecast as true:

'' == TRUE // false
0 == TRUE // false
FALSE == TRUE // false
array() == TRUE // false
'0' == TRUE // false

但是:

'a' == TRUE // true
1 == TRUE // true
'1' == TRUE // true
3.1415926 = TRUE // true
etc...

这就是为什么in_array具有可选的第3个参数来强制进行严格比较的原因.它只是使in_array进行严格的===比较,而不是==.

This is why in_array has the optional 3rd parameter to force a strict comparison. It simply makes in_array do a === strict comparison, instead of ==.

这意味着

'a' === TRUE // FALSE

这篇关于PHP的变量类型宽大处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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