Working with an array with periods in key values

末鹿安然 提交于 2019-12-17 16:45:40

问题


I'm getting data from an array. For some reason the array has key values like [3.3] which I'm having trouble retrieving data from.

I have this array [3.3] => First Name [3.6] => Last Name[2] => email@example.com.

When I try to call $array[3.3] it returns null, but when I call $array[2] I am given the e-mail. Any ideas?


回答1:


Use single quotes when referencing the key value (basically treat it like a string, that's what PHP is probably doing)

echo $array['3.3'];



回答2:


From php manual :

Floats in key are truncated to integer.

So you're trying to get $array[3] which does not exist, so you get Null




回答3:


A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.

  • http://php.net/manual/en/language.types.array.php

Since a float would always get truncated as an integer (e.g. 3.3 would always be interpreted by the array as 3) I wonder if your array is expecting a String not a float. Have you tried $array["3.3"] instead of $array[3.3]?




回答4:


I guess it has something todo with the PHP autocasting 3.3 => float

try $array['3.3']




回答5:


Floats and numeric string in key are truncated to integer.

So output this code:

$array = [1 => "a", "1" => "b", 1.5 => "c", true => "d"];
print_r($array);

would be:

Array
(
    [1] => d
)


来源:https://stackoverflow.com/questions/4542234/working-with-an-array-with-periods-in-key-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!