Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I assign properties to an object in array_reduce?

I have a simple php array that looks like this & I am looping over it to assign its keys as properties to an stdClass object & its values as the values of those keys. My code looks like this

$arr = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5];

$obj = new stdClass();

foreach ($arr as $key => $value) {
    $obj->{$key} = $value;
}

After this point, my $obj looks like this after a print in the popular laravel php repl, tinker. Its just convinient for me to work in there

 {#4867
    +"one": 1,
    +"two": 2,
    +"three": 3,
    +"four": 4,
    +"five": 5,
  }

A regular var_dump would look like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

object(stdClass)#4867 (5) {
  ["one"]=>
  int(1)
  ["two"]=>
  int(2)
  ["three"]=>
  int(3)
  ["four"]=>
  int(4)
  ["five"]=>
  int(5)
}

but that’s no biggie, my main question is why can’t i set these properties in an array_reduce using array_keys to get the key & using the array above to grab the value of that key like so;

$arr = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5];

$obj = new stdClass();

$result = array_reduce(
    array_keys($arr),
    function ($carry, $curr) use ($arr) {
        return $carry->{$curr} = $arr[$curr];
    },
    $obj
);

Trying to run this piece of code throws the error
Error Attempt to assign property "two" on int.

Am pretty sure am missing something because just passing an array with one element works, ie reducing ['one' => 1] using the same method produces an stdClass object with one property, one with a value of 1

>Solution :

Your array_reduce callback returns this expression:

return $carry->{$curr} = $arr[$curr];

But that does not return the object — it is just the value that was assigned to one object property.

You’ll want the callback to always return the carry (accumulator).

So have the callback do the assignment and then return the object:

$carry->{$curr} = $arr[$curr];
return $carry;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading