加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – in_array没有任何意义

发布时间:2020-12-13 18:15:11 所属栏目:PHP教程 来源:网络整理
导读:$arr = array( 'test' = array( 'soap' = true,),);$input = 'hey';if (in_array($input,$arr['test'])) { echo $input . ' is apparently in the array?'; } 结果: 嘿显然在阵中? 这对我没有任何意义,请解释原因.我该如何解决这个问题? 那是因为真的==’
$arr = array(
    'test' => array(
        'soap' => true,),);

$input = 'hey';
if (in_array($input,$arr['test'])) {
    echo $input . ' is apparently in the array?'; 
}

结果:
嘿显然在阵中?

这对我没有任何意义,请解释原因.我该如何解决这个问题?

那是因为真的==’嘿’由于 type juggling.你要找的是:
if (in_array($input,$arr['test'],true)) {

它强制基于===而不是==进行相等性测试.

in_array('hey',array('soap' => true)); // true

in_array('hey',array('soap' => true),true); // false

为了更好地理解类型杂耍你可以玩这个:

var_dump(true == 'hey'); // true (because 'hey' evaluates to true)

var_dump(true === 'hey'); // false (because strings and booleans are different type)

更新

如果你想知道是否设置了数组键(而不是存在一个值),你应该像这样使用isset()

if (isset($arr['test'][$input])) {
    // array key $input is present in $arr['test']
    // i.e. $arr['test']['hey'] is present
}

更新2

还有array_key_exists()可以测试阵列密钥的存在;但是,只有在相应的数组值可能为null的情况下才应使用它.

if (array_key_exists($input,$arr['test'])) {
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读