Working with an array with periods in key values

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 protected].

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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 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'];

Solution 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

Solution 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.

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]?

Solution 4

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

try $array[‘3.3’]

Solution 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"];

would be:

    [1] => d

Solution 6

I had a similar problem when adding elements into array using float keys – PHP was overwriting existing values (key 1.2 was overwritten by 1.5 etc.).

Based on this SO thread I add cast key to string:

$options[(string)$value] = new TpValueModelOption($value, $label);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply