3
public function getInvoiceItemsByType($type)
{
    return $this->invoiceItems->filter(function ($invoice) use ($type) {
        /** @var InvoiceItem $invoice */
        return $invoice->getType() == $type;
    }
    );
}

public function getInvoiceItemsByType($type) {
    foreach ($this->invoiceItems as $invoice) {
        if ($invoice->getType() == $type) {
            return $invoice;
        }
    }
    return null;
}

is there a difference between these two functions ? Someone told me that there is one but I can't manage to find what is it precisely and how one function instead of the other would affect my code

Pradeep
  • 9,667
  • 13
  • 27
  • 34
j.y
  • 37
  • 3

1 Answers1

6

The difference is that

return $this->invoiceItems->filter(function ($invoice) use ($type) {
    /** @var InvoiceItem $invoice */
    return $invoice->getType() == $type;
});

Will return all items which match or an empty ArrayCollection when nothing is found.


While

foreach ($this->invoiceItems as $invoice) {
    if ($invoice->getType() == $type) {
        return $invoice;
    }
}
return null;

Will only ever return the first item of the array that matches $invoice->getType() == $type or null if it does not exist at all.

Robert
  • 5,703
  • 2
  • 31
  • 32