0

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

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

Richard
  • 412
  • 6
  • 9
  • 1
    You are overthinking it. https://3v4l.org/RIJi8 – mickmackusa Jan 31 '23 at 21:32
  • haha, I know there are many ways to do it, I was just curious why the array_reduce way was giving me an error, turns out it was a wrong return from the callback - otherwise i wouldnt actually use it as a solution – Richard Jan 31 '23 at 22:10
  • 1
    To clarify the reason for the two closing pages: the first dupe target explains how to perform the task without `array_reduce()` and the second dupe target explains how to repair the coding attempt with `array_reduce()`. – mickmackusa Feb 01 '23 at 00:19

1 Answers1

1

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;
trincot
  • 317,000
  • 35
  • 244
  • 286