php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #51915 numeric string key escaped in type change
Submitted: 2010-05-26 08:30 UTC Modified: 2011-02-09 09:23 UTC
Votes:7
Avg. Score:3.1 ± 1.2
Reproduced:5 of 7 (71.4%)
Same Version:1 (20.0%)
Same OS:3 (60.0%)
From: laruence at yahoo dot com dot cn Assigned:
Status: Not a bug Package: JSON related
PHP Version: 5.2.13 OS: linux
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: laruence at yahoo dot com dot cn
New email:
PHP Version: OS:

 

 [2010-05-26 08:30 UTC] laruence at yahoo dot com dot cn
Description:
------------
php treat numeric string key as interge,

bug sometimes there is some exception.

for example:
  while change a std object to array, numeric string key doesn't cast to number 

Test script:
---------------
<?php
$data = array(
    123 => 'laruence',
    "03"=> 'baidu',
);

$value = json_encode($data);
$obj   = json_decode($value);
$arr   = (array)$obj;
var_dump($arr);
?>

Expected result:
----------------
array(2) {
  [123]=>
  string(8) "laruence"
  ["03"]=>
  string(5) "baidu"
}


Actual result:
--------------
array(2) {
  ["123"]=>
  string(8) "laruence"
  ["03"]=>
  string(5) "baidu"
}


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-05-27 04:15 UTC] laruence at yahoo dot com dot cn
-Type: Bug +Type: Feature/Change Request -Package: JSON related +Package: Scripting Engine problem
 [2010-05-27 04:15 UTC] laruence at yahoo dot com dot cn
change bug to Feature , nhancement
 [2010-06-07 10:03 UTC] xiezhenye at gmail dot com
there is an easier way to build such an array.

$obj = new stdClass;
$obj->{'123'} = 1;
$arr = (array) $obj;
var_dump($obj);
 [2010-06-08 11:55 UTC] tony2001@php.net
-Package: Scripting Engine problem +Package: JSON related
 [2011-02-09 09:23 UTC] scottmac@php.net
-Status: Open +Status: Bogus
 [2011-02-09 09:23 UTC] scottmac@php.net
When an array is of mixed type or doesn't contain sequential keys it has to be 
treated as a hash and not as an integer

json_encode() turns the integer keys into strings which it has to do to be valid 
json.

On json_decode() it see's string keys instead of numeric since this is a hash 
not an array.

There is nothing unexpected happening here.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Nov 21 17:01:32 2024 UTC