Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with an array with periods in key values

Tags:

arrays

php

period

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?

like image 428
Brooke. Avatar asked Dec 27 '10 22:12

Brooke.


People also ask

Can an array have keys?

Arrays can only have integers and strings as keys. You can simulate arrays and use objects as keys with SplObjectStorage .

How do you find the key and value of an array?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

Can array key be an array?

This is not possible - array keys must be strings or integers.


2 Answers

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

like image 96
Mironor Avatar answered Sep 30 '22 16:09

Mironor


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'];
like image 25
Brad Christie Avatar answered Sep 30 '22 16:09

Brad Christie