php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #32671 Array keys converted from float to integer
Submitted: 2005-04-11 16:19 UTC Modified: 2005-04-12 09:41 UTC
From: marek at lewczuk dot com Assigned:
Status: Closed Package: Documentation problem
PHP Version: 5.0.3 OS: Linux
Private report: No CVE-ID: None
 [2005-04-11 16:19 UTC] marek at lewczuk dot com
Description:
------------
Suppose we have a float value: $value = 345.332 and we want to use this value as an array key: $array[$value] = $value. This will cause that key will be truncated to integer 345 not to string "345.332". It is written in the manual that:

"...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")..."

From this point of view floats should be converted to strings. I'm not saying that this is a bug, rather I would like to be sure if this is a proper behavior. Simple solution is to type cast float value to string (string), but we have to know that given value is a float (and sometimes, we don't know that). IMHO any other type than integer should be treat as string.



Reproduce code:
---------------
$value = 345.654;
$array = array();
$array[$value] = "Float";

Expected result:
----------------
array (
 "345.654" => "Float"
)

Actual result:
--------------
array (
 "345" => "Float"
)

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-04-11 16:24 UTC] marek at lewczuk dot com
One more example, what problem this "bug/behavior" may cause:
$value1 = 345.654;
$value2 = 345.655;
$array = array();
$array[$value1] = $value1;
$array[$value2] = $value2;

Result:
array (
  345 => 345.655,
)

If this is a normal behavior you should put a note about this in the manual.
 [2005-04-11 17:45 UTC] sniper@php.net
This is nothing new for PHP 5, same happens with PHP 4.

 [2005-04-11 20:46 UTC] marek at lewczuk dot com
Maybe is same for PHP4 - I just never had a chance check how this works. So, I understand that this is a proper behavior, right ?
 [2005-04-12 09:41 UTC] vrana@php.net
This bug has been fixed in the documentation's XML sources. Since the
online and downloadable versions of the documentation need some time
to get updated, we would like to ask you to be a bit patient.

Thank you for the report, and for helping us make our documentation better.

"Floats in key are truncated to integer."
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 25 10:01:29 2024 UTC