首页 > 解决方案 > PHP in_array 函数给出恼人的结果

问题描述

PHP 7

in_array('one', [0 => 0]) //true
in_array('one', [0]) //true
in_array('one', array_keys([0 => 0])); //true

预期结果为 FALSE,因为显然给定数组中没有字符串值,也没有“真”值(字符串可以评估为真并匹配)

如果我们假设任何类型比较 0 整数总是与 PHP 中的 false 进行比较,而 String 与 true 进行比较,那么为什么这仍然有效呢?

我知道,严格模式存在并且工作正常,但无论如何绝对令人讨厌为什么会发生这种情况。有什么解释吗?

标签: phparraysphp-7

解决方案


The answer to your question is here:

Comparing String to Integer gives strange results

Same situation when "one" == 0 as in your examples.

TL:DR - on string-to-integer comparison the string will be converted to integer, not the integer to string, so "one" will be converted to 0


推荐阅读