首页 > 解决方案 > 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 数组键。

标签: phparrayskeyarray-key-exists

解决方案


如果您使用浮点数作为键,它将自动转换为 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


推荐阅读