0

I have a big set of time records for a project and I want to filter out all but those posted by a single employee.

array_walk($timeRecords, function($timeRecord, $index) use ($employee) {
    if ($timeRecord->employeeId != $employee->id) {
        unset($timeRecords[$index]);
    }
});

You can see what I'm trying to do. How do you go about doing this with anon functions and closures? Obviously $timeRecords is not defined inside the anonymous function. Thanks.

JamesNZ
  • 482
  • 5
  • 17

1 Answers1

0

Calimero pointed out that's the wrong tool for the job. The desired effect can be achieved using array_filter. Array_walk appears to be designed for modifying individual array items by reference.

This is how to achieve what I was wanting.

$timeRecords = array_filter($timeRecords, function($timeRecord) use ($employee) {
    if ($timeRecord->EmployeeId == $employee->EmployeeId) {
        return $timeRecord;
    }
});
JamesNZ
  • 482
  • 5
  • 17
  • 1
    Maybe you want to take a look again at the docs of `array_filter()`, you just need to return true/false if you want to keep the element or not – Rizier123 Nov 24 '15 at 19:55
  • 1
    Ah I missed that. It's right there in the docs (http://php.net/manual/en/function.array-filter.php). Thanks. – JamesNZ Nov 24 '15 at 19:57