-1

我想知道是否可以帮助理解为什么 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 数组键。

4

2 回答 2

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

于 2021-08-31T13:55:27.677 回答
1

You can use strings as keys, so you won't have float to int conversion. When necessary to compare, you can convert it back to float:

<?php
$arr['1'] = 'test';
$arr['1.1'] = 'anothertesty';

foreach ($arr as $key => $value) {
    if (array_key_exists($key, $arr)) {
        echo 'found' . $key;
    }
}
于 2021-08-31T14:15:45.900 回答