php - 如果传递一个 0,为什么 php 的 in_array 会返回 true?
问题描述
在下面in_array(0, $array)
评估为true
。这让我很惊讶。我预计false
。
我知道添加第三个参数来表示严格的检查in_array(0, $array, true)
会给我想要的结果。
也就是说,我很好奇为什么 in_array(0, $array)
评估为true
. 起初我以为它只是在 0 索引处看到一个字符串,但in_array(1, $array)
计算false
结果似乎并不能解释它。
示例: 此处可运行的小提琴
<?php
$array = [
'inputs',
'app',
'post',
'server',
];
echo in_array('inputs', $array) ? '"inputs" is in the array...' : '';
echo "\n";
echo in_array(0, $array) ? '0 is also in the array!' : '';
echo "\n";
echo in_array(1, $array) ? '1 is also in the array!' : '1 is NOT in the array!';
输出:
"inputs" is in the array...
0 is also in the array! <---- huh?
1 is NOT in the array!
解决方案
这是因为默认情况下in_array
使用松散比较,因此当您0
作为输入传递时,它会尝试将数组中的字符串值转换为整数,并且它们都显示为 0(因为它们都不是以数字开头;请参阅手册) ,导致in_array
返回true
。它为输入返回 false,1
因为所有比较值都是 0。
您将看到类似的行为array_keys
:
print_r(array_keys($array, 0));
输出:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
表示array_keys
认为数组中的每个值都是 0。
如果您使用该strict
参数,in_array
否则array_keys
您将避免此问题,即
echo in_array(0, $array, true) ? '0 is also in the array!' : '0 is NOT in the array!';
print_r(array_keys($array, 0, true));
输出:
0 is NOT in the array!
Array
(
)
推荐阅读
- r - 有没有办法克隆由 simmer 创建的“包装”对象?
- swift - 属性 X 不是 T 的成员
- asp.net-core - IIS 的 AspNetCoreModule 模块实现了什么?
- java - Intellij 无法在私有存储库中获取 Maven 工件
- javascript - 获取 blob 数据后,附件 csv 文件格式不正确
- python - 在 Python 中将波转换为分贝
- avx - 在 AVX 中进行线性平均的最短方法
- php - PHP array_diff_assoc 在同一个变量中
- python-3.x - 迭代字典“int对象不可下标”Python 3中的整数键时出错
- java - JavaFX 中的可编辑表格单元格在尝试再次编辑时显示旧值