php – in_array没有任何意义

前端之家收集整理的这篇文章主要介绍了php – in_array没有任何意义前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_502_1@$arr = array( 'test' => array( 'soap' => true,),); $input = 'hey'; if (in_array($input,$arr['test'])) { echo $input . ' is apparently in the array?'; }

结果:
嘿显然在阵中?

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

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

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

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

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

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

更新

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

@H_502_1@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的情况下才应使用它.

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

猜你在找的PHP相关文章