diff --git a/src/iter.php b/src/iter.php index 0d487b4..2e0e672 100644 --- a/src/iter.php +++ b/src/iter.php @@ -1290,6 +1290,25 @@ function tap(callable $function, iterable $iterable): \Iterator { } } +/** + * Returns the last value of the specified iterable. + * + * @template T + * + * @param iterable $iterable Iterable. + * + * @return T|null Last value of the iterable if it contains values, otherwise null. + */ +function last(iterable $iterable) { + if (is_array($iterable)) { + return count($iterable) ? end($iterable) : null; + } + + foreach ($iterable as $value) {} + + return $value ?? null; +} + /* * Python: * compress() diff --git a/test/iterTest.php b/test/iterTest.php index 9b79854..b6fc71f 100644 --- a/test/iterTest.php +++ b/test/iterTest.php @@ -644,6 +644,16 @@ public function testTap() { toArray(tap([$mock, 'foo'], [1, 2, 3])) ); } + + public function testLast() { + self::assertSame(5, last((function () { + yield from range(1, 5); + })())); + self::assertNull(last(new \EmptyIterator())); + + self::assertSame(3, last(range(1, 3))); + self::assertNull(last([])); + } } class _CountableTestDummy implements \Countable {