【问题标题】:in_array returns true if needle is 0 [duplicate]如果 needle 为 0,in_array 返回 true [重复]
【发布时间】:2013-05-23 04:06:34
【问题描述】:

我对@9​​87654321@ 函数有疑问。下面的测试返回true

in_array(0, array('card', 'cash'))

怎么可能,怎么预防?

然而

in_array(null, array('card', 'cash'))

返回false

【问题讨论】:

  • (int) 0 in (int)'card'?
  • LOOSE TYPING...您正在将数字与字符串进行比较,因此字符串将转换为数字,在这种情况下为 0,并且 0 == 0。使用可选的 STRICT 参数

标签: php arrays conditional-statements


【解决方案1】:

将任何不以数字开头的字符串转换为数字会在 PHP 中生成0。这正是将0 与某个字符串进行比较时发生的情况。请参阅PHP docs 了解有关如何完成各种类型之间的比较的详细信息。

使用in_array 的第三个参数(设置为true)来避免松散的类型比较。

in_array(0, array('card', 'cash'), true) === false

【讨论】:

  • 好吧,这就是我需要的答案。谢谢!
【解决方案2】:

当您在in_array 中进行比较时 string 在比较不兼容的数据类型时转换为 int 这意味着cashcard被转换为0

这都是因为类型转换

你有两个选择

1 .类型转换

in_array(string(0), array('card', 'cash'))) === false;

2 .在 in_array 上使用 third parametertrue,这将匹配数据类型

in_array(0, array('card', 'cash'), true) === false;

documentation

【讨论】:

  • 哎呀!!回答这个问题有点晚了..
【解决方案3】:

您可以通过使用 'strict' 参数来防止它:

var_export(in_array(0, array('card', 'cash'), true));

var_export(in_array(null, array('card', 'cash'), true));

在这两种情况下都返回 false。

来自the docs to in_array()

If the third parameter strict is set to TRUE then the in_array()
function will also check the types of the needle in the haystack.

【讨论】:

    【解决方案4】:

    答案可以将0 转换为字符串,所以:

    in_array((string) 0, array('card', 'cash'))
    

    请记住,0 可以是一些变量,因此强制转换可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-07
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多