简体   繁体   English

关联数组键转换浮点字符串

[英]Associative Array Key Casting Float String

In my code, I have generated an associative array with keys as floats, however the PHP documentation states that when they become key's in the array they are SUPPOSED to be cast to integers. 在我的代码中,我生成了一个以键为浮点数的关联数组,但是PHP文档指出,当它们成为数组中的键时,应该将其强制转换为整数。 Instead, they are being cast to strings (which is actually better for me so I'm not complaining). 相反,它们被强制转换为字符串(这实际上对我来说更好,所以我没有抱怨)。

The problem is that when I try to access these keys using a float as the key value, it casts only the floats with .5 to integers and creates a new entry in the array. 问题是,当我尝试使用浮点数作为键值来访问这些键时,它仅将具有.5的浮点数转换为整数,并在数组中创建新条目。 Seems like peculiar behavior. 似乎是特殊行为。

Example: 例:

var_dump( $array );

Output: 输出:

array(9) {
[0] =>
int(0)
[1.25] =>
int(0)
[2.5] =>
int(0)
....}

When I try to access the value 2.5 like so, 当我尝试像这样访问值2.5时,

array[2.5]++;

a new entry in the array is made at array[2] However if I try to access the array at array[1.25]++; array[2]处创建了一个数组中的新条目。但是,如果我尝试在array[1.25]++;处访问该数组array[1.25]++; I successfully add 1 to the value at key: 1.25 我成功将键值1.25加1

Any ideas? 有任何想法吗?

I would just stick with strings all the time: 我会一直坚持下去:

$a = array(
    '0' => 0,
    '1.25' => 0,
    '2.5' => 0
);

$a['2.5']++;
echo $a['2.5'] . "\n";
var_dump($a);

Output is: 输出为:

1
array(3) {
  [0]=>
  int(0)
  ["1.25"]=>
  int(0)
  ["2.5"]=>
  int(1)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM