Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce an array of objects in PHP [duplicate]

Tags:

arrays

php

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?

like image 365
Jordi Nebot Avatar asked Sep 05 '26 10:09

Jordi Nebot


1 Answers

You might be looking for array_column(), which takes the values of the given column:

$result = array_column($largeArray, 'name');// take all values with the key 'name'

// If you want it with a slash:
echo implode(" / ", $result);

Doesn't need much more explanation. Which is the kind of code you should go for. Weird functionality that feels fancy, but nobody can understand is worse. You might understand what it does now, but if you leave it alone for 6 months and come back, you've forgotten it just as much.

Often: maintainability > complexity (and sometimes even >performance)

like image 188
Martijn Avatar answered Sep 07 '26 00:09

Martijn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!