forked from lstrojny/functional-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLast.php
More file actions
37 lines (31 loc) · 971 Bytes
/
Last.php
File metadata and controls
37 lines (31 loc) · 971 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
/**
* @package Functional-php
* @author Lars Strojny <lstrojny@php.net>
* @copyright 2011-2021 Lars Strojny
* @license https://opensource.org/licenses/MIT MIT
* @link https://github.com/lstrojny/functional-php
*/
namespace Functional;
use Functional\Exceptions\InvalidArgumentException;
use Traversable;
/**
* Looks through each element in the collection, returning the last one that passes a truthy test (callback).
* Callback arguments will be element, index, collection
*
* @param Traversable|array $collection
* @param callable $callback
* @return mixed
* @no-named-arguments
*/
function last($collection, ?callable $callback = null)
{
InvalidArgumentException::assertCollection($collection, __FUNCTION__, 1);
$match = null;
foreach ($collection as $index => $element) {
if ($callback === null || $callback($element, $index, $collection)) {
$match = $element;
}
}
return $match;
}