phpfunctionrefactoringlaravel-collectionfn

Different results for function() and fn(). PHP


I have a problem.

$this->allIds->each(function ($id) {
    $this->checked[$id] = $this->checkedAll;
});

And this:

$this->allIds->each(fn($id) => $this->checked[$id] = $this->checkedAll);

return different results... Why? :) In full version i have this: Result with function() In short version i have this: Result with fn()

Thanks :)


Solution

  • When using each() to iterate over a Laravel collection, returning false stops the iteration:

    If you would like to stop iterating through the items, you may return false from your closure

    In your case, $this->checkedAll is false, so the closure returns false and you get only one element in your $this->checked array.