php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #54651 Modify existing elements in Array created from Object
Submitted: 2011-05-02 15:51 UTC Modified: 2011-05-03 05:19 UTC
From: smartcoding at live dot com Assigned:
Status: Duplicate Package: Class/Object related
PHP Version: 5.3.6 OS: *
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 this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: smartcoding at live dot com
New email:
PHP Version: OS:

 

 [2011-05-02 15:51 UTC] smartcoding at live dot com
Description:
------------
After converting and Object to an associative Array using (array) variable type 
prefix cannot access and modify existing elements.
Tested in all latest PHP versions with and without modules.

Test script:
---------------
//create object
$obj->{1} = 'something';

//convert object to array
$arr = (array)$obj;

//modify element
$arr[1] = 'something else';

//dump final array
print_r($arr);

Expected result:
----------------
Array ( [1] => something else )

Actual result:
--------------
Array ( [1] => something [1] => something else )

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-05-02 16:17 UTC] felipecg00 at gmail dot com
I can reproduce it in 5.3.3.
Seems like it happens with numeric indexes only:

//create object
$obj->q = 'something';

//convert object to array
$arr = (array)$obj;

//modify element
$arr['q'] = 'something else';

//dump final array
print_r($arr);

Result:
Array
(
    [q] => something else
)


This way works:

//create object
$obj = new stdClass(array(
	1 => 'something' 
));

//convert object to array
$arr = (array) $obj;

//modify element
$arr[1] = 'something else';

//dump final array
print_r($arr);

Results:
Array
(
    [1] => something else
)
 [2011-05-02 16:42 UTC] smartcoding at live dot com
@felipecg00:
1) yes, this happens only with numeric indexes
2) in your second snippet you are creating an empty 
object and then assigning new element instead of modifying existing one. Dump your 
initial object in the beginning to see what I mean.
 [2011-05-02 17:08 UTC] felipecg00 at gmail dot com
You are right! Don't know why I thought that would work. Guess I need to sleep a bit.
 [2011-05-03 05:19 UTC] aharvey@php.net
-Status: Open +Status: Duplicate
 [2011-05-03 05:19 UTC] aharvey@php.net
This is documented behaviour, and a duplicate of bug #45959 -- in essence, it's a known issue, but not one that's likely to be fixed for performance reasons.
 
PHP Copyright © 2001-2022 The PHP Group
All rights reserved.
Last updated: Sat Jan 29 03:03:35 2022 UTC