That is - array_reduce() is exactly what you need:
class Bar { protected $id; public function __construct($id) { $this->id = $id; } public function getId() { return $this->id; } } class Foo { protected $bar; public function __construct(Bar $bar) { $this->bar = $bar; } } $oldObjects = [new Bar('x'), new Bar('y'), new Bar('z')]; $newObjects = array_reduce($oldObjects, function($current, Bar $obj) { $current[$obj->getId()] = new Foo($obj); return $current; }, []);
This will do everything in place without wasting memory on additional arrays, e.g. array_combine()
However, I would suggest using such constructions when they are needed. Using this just because it “looks better” might not be a good idea, since simple loops are more readable in most cases.
source share