php - PHP - 当键包含小数位时如何检查数组键是否存在?
问题描述
我想知道是否可以帮助理解为什么 array_key_exists 在使用小数位时找不到我的密钥?
<?php
$arr[1] = 'test';
$arr[1.1] = 'anothertesty';
foreach ($arr as $key => $value) {
if (array_key_exists($key, $arr)) {
echo 'found' . $key;
}
}
任何人都可以请告知使用此的正确方法是什么。我需要找到 1.1 数组键。
解决方案
如果您使用浮点数作为键,它将自动转换为 int
看下面的文档
https://www.php.net/manual/en/language.types.array.php
键可以是 int 或字符串。该值可以是任何类型。
此外,还会发生以下关键转换:
[...]
浮点数也被转换为整数,这意味着小数部分将被截断。例如,密钥 8.7 实际上将存储在 8 下。
意味着,您的浮点数被转换为 int 和
$arr[1.1] = 'test';
现在可以通过
echo $arr[1]
Additionally in your case the first assignment
$arr[1] = 'test';
will be immediately overwritten with anothertesty
by calling
$arr[1.1] = 'anothertesty';
Thats why in the end you will just find 1
as the only key in your array
推荐阅读
- javascript - 如何在使用 jquery ajax 成功后停止递增存储数组?
- dataset - 结果显示在 Google DATASET 搜索中需要多长时间?
- python - 选择性分组,np.where Pandas/Python 查询
- java - 如何在java中为方法添加参数
- python-3.x - 在命令行中执行多个 python 文件
- android - 如何调用选项卡式活动中片段结果的显式意图?
- javascript - 滑块中的分页,Jquery
- javascript - 执行算术运算后对象属性不返回值
- java - 从 @MvcTest 注释测试调用时,Spring Boot Controller 的行为不同
- r - 使用 ggscatter 绘制不等 x 和 y 的散点图