首页 > 解决方案 > 如果传递一个 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!

标签: phparrays

解决方案


这是因为默认情况下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
(
)

3v4l.org 上的演示


推荐阅读