phparraysobjectoopprivate-members

Implode column of private values from an array of objects


I have an array of objects and I want to implode a specific private property from each object to form a delimited string.

I am only interested on one of the properties of that array. I know how to iterate the data set via foreach() but is there a functional-style approach?

$ids = "";
foreach ($itemList as $item) {
    $ids = $ids.$item->getId() . ",";
}
// $ids = "1,2,3,4"; <- this already returns the correct result

My class is like this:

class Item {
    private $id;
    private $name;

    function __construct($id, $name) {
        $this->id=$id;
        $this->name=$name;
    }
    
    //function getters.....
}

Sample data:

$itemList = [
    new Item(1, "Item 1"),
    new Item(2, "Item 2"),
    new Item(3, "Item 3"),
    new Item(4, "Item 4")
];

Solution

  • Use array_map before you implode:

    $ids = implode(",", array_map(function ($item) {
        return $item->getId();
    }, $itemList));