Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/iter.php
Original file line number Diff line number Diff line change
Expand Up @@ -1290,6 +1290,19 @@ function tap(callable $function, iterable $iterable): \Iterator {
}
}

/**
* Returns the last value of the specified iterable.
*
* @param iterable $iterable Iterable.
*
* @return mixed Last value of the iterable if it contains values, otherwise null.
*/
function last(iterable $iterable): mixed {
foreach ($iterable as $value) {}

return $value ?? null;
}

/*
* Python:
* compress()
Expand Down
5 changes: 5 additions & 0 deletions test/iterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,11 @@ public function testTap() {
toArray(tap([$mock, 'foo'], [1, 2, 3]))
);
}

public function testLast() {
self::assertSame(3, last(range(1, 3)));
self::assertNull(last(new \EmptyIterator()));
}
}

class _CountableTestDummy implements \Countable {
Expand Down
Loading