msw
msw

Reputation: 3

php foreach duplicate first item

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

Upvotes: 0

Views: 113

Answers (1)

CMR
CMR

Reputation: 1416

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);

Upvotes: 3

Related Questions