14

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?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Brooke.
  • 3,691
  • 13
  • 49
  • 80

6 Answers6

31

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'];
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • 3
    one thing: if your '3.0' is by any chance in a variable (i.e.`$x = '3.0';`) and you're trying to do `$myarr[$x] = "Wow!"`, you'll need to do something like `$myarr["'{$x}'"] = "Wow!"`. Just my 5 cents... – hummingBird Oct 03 '14 at 13:43
  • 1
    For the key being referenced by a variable, this worked for me: `$myarr["$x"]` – Steve Taylor Feb 04 '15 at 23:58
19

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

Mironor
  • 1,157
  • 10
  • 25
8

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

GSP
  • 3,763
  • 3
  • 32
  • 54
  • 2
    ""8" will be interpreted as 8." It's worth noticing that on platforms where INT uses 32 bits, when string is in the standard representation of an integer that needs more then 32 bits (for example "3206519370"), then it will stay as string key and won't be converted to int (which would result in overflow). – Dawid Ohia Mar 24 '12 at 13:57
2

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

try $array['3.3']

Michele
  • 6,126
  • 2
  • 41
  • 45
2

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
)
0

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);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ales
  • 381
  • 6
  • 8