Reduce an array of objects in PHP

Viewed 4110

I have an array of objects. Something like this:

$my_array = [
    (object) ['name' => 'name 0'],
    (object) ['name' => 'name 1'],
    (object) ['name' => 'name 2'],
];

And I'd like to reduce it to a concatenation of all name properties like:

name 0 / name 1 / name 2

One way would be:

$result = [];
foreach ($my_array as $item) {
    $result[] = $item->name;
}
echo implode(' / ', $result);

But I'd prefer something more compact, like using array_map:

implode(' / ', array_map(function($item) {
    return $item->name; 
}, $my_array ));

Given that in fact I want to reduce and array to a string I thought it would be cleaner with array_reduce but the only solution I can come out with is:

array_reduce($my_array, function($carry, $obj) {
    return empty($carry) ? $obj->name : $carry .= " / $obj->name"; 
});

Yet it doesn't feel cleaner... So the question is simple:

Can anybody think of an understandable better/cleaner solution?

2 Answers
Related