[英]How can I match an exact numeric string using in_array?
我使用in_array
在数组中搜索一个数字。 当我搜索084
我得到了true
。 之后我搜索了84
,但我得到了true
和 "084" 值。
我怎样才能避免这种情况?
这是进行检查的代码:
if (in_array(strval($_GET['search']), $vall))
{
array_push($allwin,$number_array[0][0]);
}
我正在测试的数组是从具有如下值的 JSON 中提取的:
["\u0e40\u0e25\u0e02\u0e17\u0e49\u0e32\u0e223\u0e15\u0e31\u0e27","084","375"]
因为在数字上, 084
和84
都表示相同的数字。 由于默认情况下in_array
使用松散比较,它将匹配它们,因为它将在内部应用类型转换并且两者都将转换为84
,因为它们是数字。
如果您查看in_array
文档,您会看到它有第三个参数:
in_array ( mixed $needle , array $haystack , bool $strict = false ) : bool
这决定了应该使用松散比较还是严格比较。 将它设置为true
会给你想要的结果。
例如,如果您要运行以下命令:
var_dump(in_array(84, ['084', '756', '34']));
var_dump(in_array(84, ['084', '756', '34'], true));
var_dump(in_array('84', ['084', '756', '34'], true));
var_dump(in_array('084', ['084', '756', '34'], true));
他们会输出:
true // loose comparison, 84 == '084', both cast to numbers resulting in 84 being compared to 84
false // strict comparison, 84 !== '84', as one is int and the other string
false // strict comparison, '84' !== '084', as they're not identical strings, the second one has an extra character at the beginning
true // strict comparison, '084' === '084', identical strings
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.