1
votes

QUESTION


Why does this code produce different results when run in php5.6 vs php7.0?

BACKGROUND


I have the following code:

<?php
$assoc_array = [
    'a' => 1,
    'b' => 2,
    'c' => 3,
    'd' => 4
];
$index_array = ['a','b','c','d'];
$object = new \StdClass;

foreach($index_array as $item) {
    $object->$assoc_array[$item] = "";
}

print_r($object);

When I run it in ubuntu 17.4, apache 2.4.25, php 7.0, I get this:

Notice: Array to string conversion in /var/www/html/file.php on line 12
Notice: Array to string conversion in /var/www/html/file.php on line 12
Notice: Array to string conversion in /var/www/html/file.php on line 12
Notice: Array to string conversion in /var/www/html/file.php on line 12

stdClass Object ( 
    [Array] => Array ( 
        [a] => 
        [b] => 
        [c] => 
        [d] => 
    ) 
)

When I run it in the same environment, but switch to php 5.6, I get this:

stdClass Object (
    [1] =>
    [2] =>
    [3] =>
    [4] =>
)

It's not breaking my code, I just got really hung up on why it was different and didn't where to start my research.

NB. It's the object I'm interested in here, not the notices - error reporting is on in both.

1

1 Answers

1
votes

You can't do this in PHP7: $object->$assoc_array[$item] = ""; As you see, you get a notice, replace your code by this one:

<?php
$assoc_array = [
    'a' => 1,
    'b' => 2,
    'c' => 3,
    'd' => 4
];
$index_array = ['a','b','c','d'];
$object = new \StdClass;

foreach($index_array as $item) {
    $object->{$assoc_array[$item]} = "";
}

print_r($object);

You can find more informations here: https://github.com/tpunt/PHP7-Reference#uniform-variable-syntax