4

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")
];
3
  • Do you actually need "cheaper", as opposed to clear, obvious code? If not, just go for the loop. Commented Aug 20, 2014 at 16:26
  • When I say "cheaper" I mean resource friendly. Commented Aug 20, 2014 at 16:28
  • Probably the most expensive resource is you, and future maintainers. Keep the code as simple and readable as possible, and if you find you need to optimise you can always come back when you've benchmarked and pinpointed the problem areas. Commented Aug 21, 2014 at 14:43

3 Answers 3

6

Use array_map before you implode:

$ids = implode(",", array_map(function ($item) {
    return $item->getId();
}, $itemList));
Sign up to request clarification or add additional context in comments.

Comments

0

You've "yatta-yatta"ed your getter scripting, so I'll demonstrate two functional style approaches for two getter approaches.

  1. If the class contains an explicitly named method: (Demo)

    public function getId()
    {
        return $this->id;
    }
    

    then you can use 2 cycles:

    echo implode(',', array_map(fn($obj) => $obj->getId(), $itemList));
    

    or 1 cycle with a conditional:

    echo array_reduce(
             $itemList,
             fn($result, $obj) => $result . ($result ? ',' : '') . $obj->getId()
         );
    



  2. If the class contains the magic method __get(): (Demo)

    public function __get($prop)
    {
        return $this->$prop;
    }
    

    then you can use 2 cycles:

    echo implode(',', array_map(fn($obj) => $obj->id, $itemList));
    

    or 1 cycle with a conditional:

    echo array_reduce(
             $itemList,
             fn($result, $obj) => $result . ($result ? ',' : '') . $obj->id
         );
    

Comments

-3

You can simply use $ids = implode(',',$itemList);

1 Comment

That is if the __toString returns $id. The __toString return a different thing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.