0

For object created from array foreach cycle go through first item twice

$list = (object)['a' => 1, 'b' => 2];
echo json_encode($list);

$pointers = [];
foreach($list as $n => $v)
    $pointers[] = &$list->$n;

var_dump($pointers);

json returns 2 items, pointers at end returns 3 items. What can be wrong?

But if I create object as stdClass, it works as expected.

$list = new stdClass();
$list->a = 1;
$list->b = 2;
echo json_encode($list);

$pointers = [];
foreach($list as $n => $v)
    $pointers[] = &$list->$n;

var_dump($pointers);

json returns 2 items, pointers at end returns 2 items

6
  • The pointer array is returning 2 items ideone.com/yWDVh3 . Check it out. Commented Mar 21, 2017 at 14:19
  • I don't know exactly but this might be related with pointer. If you change to $list->$n in your first example you correctly have 2 items. Maybe there is some additional pointer defined when casting to (object). Need to check that out. Commented Mar 21, 2017 at 14:20
  • @Ayush In php 7 i have this output {"a":1,"b":2}array(3) { [0]=> &int(1) [1]=> &int(1) [2]=> &int(2) } but it works fine in php 5.6 Commented Mar 21, 2017 at 14:22
  • 7.1 returns with array(2), seems to be just in 7.0.* Commented Mar 21, 2017 at 14:23
  • It's because of the reference call, $list->$n works fine. Commented Mar 21, 2017 at 14:31

1 Answer 1

3

It appears to be an oddity with PHP 7.0, as it works as expected in 7.1 and < 7.

You may have to do something like this instead:

$list = (object)['a' => 1, 'b' => 2];
echo json_encode($list);

$pointers = [];
$items = get_object_vars($list);

foreach($items as $key => $val){
    $pointers[] = &$list->$key;
}


var_dump($pointers);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.