in_array 函数在处理稀疏数组时可能会出现误判的情况,因为它只会检查数组中是否存在指定的值,而不会检查值的索引。
为了解决这个问题,你可以使用 array_flip 将数组的键值对进行翻转,然后再使用 in_array 进行查找。这样,你就可以通过值的索引来判断它是否存在于数组中。
以下是一个示例代码:
$sparseArray = [0 => 'a', 2 => 'c'];$flippedArray = array_flip($sparseArray);if (in_array('c', $flippedArray)) { echo "Value 'c' exists in the sparse array";} else { echo "Value 'c' does not exist in the sparse array";}输出结果为:
Value 'c' exists in the sparse array需要注意的是,这种方法会改变原数组的键值对顺序,如果需要保持原始顺序,可以使用以下代码:
$sparseArray = [0 => 'a', 2 => 'c'];$keys = array_keys($sparseArray);$flippedArray = [];foreach ($keys as $key) { $flippedArray[$sparseArray[$key]] = $key;}if (in_array('c', $flippedArray)) { echo "Value 'c' exists in the sparse array";} else { echo "Value 'c' does not exist in the sparse array";}输出结果为:
Value 'c' exists in the sparse array 

