You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中当数组键包含小数位时如何检测键是否存在

问题原因

PHP 数组的键仅支持整数(int)和字符串(string)两种类型,当你传入浮点数作为键时,PHP 会自动对浮点数做向下取整的强制类型转换,转为整数类型。
你写的$arr[1.1] = 'anothertesty';实际会被解析为$arr[(int)1.1] = 'anothertesty';也就是$arr[1] = 'anothertesty';,会直接覆盖之前赋值的$arr[1] = 'test',数组从始至终都不存在键为1.1的元素,自然array_key_exists无法检测到。你可以在赋值后执行var_dump($arr)验证,会看到数组中只有一个键为1的元素。

正确处理方案

如果需要保留小数作为数组键,必须将小数转为字符串类型后再作为键使用,检测时也要传入字符串格式的键:

<?php
$arr[1] = 'test';
// 将小数转为字符串作为键
$arr[(string)1.1] = 'anothertesty';
// 也可以直接写为 $arr['1.1'] = 'anothertesty';

// 直接检测字符串键
if (array_key_exists('1.1', $arr)) {
    echo 'found 1.1' . PHP_EOL;
}

// 遍历场景也可以正常检测
foreach ($arr as $key => $value) {
    if (array_key_exists($key, $arr)) {
        echo 'found ' . $key . PHP_EOL;
    }
}

上述代码运行输出如下:

found 1.1
found 1
found 1.1

如果你的检测键是动态浮点类型变量,检测前也需要先转字符串:

$searchKey = 1.1;
if (array_key_exists((string)$searchKey, $arr)) {
    echo 'found ' . $searchKey;
}

内容的提问来源于stack exchange,提问作者lky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 21:09:04