Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
19 changes: 19 additions & 0 deletions src/iter.php
Original file line number Diff line number Diff line change
Expand Up @@ -1290,6 +1290,25 @@ function tap(callable $function, iterable $iterable): \Iterator {
}
}

/**
* Returns the last value of the specified iterable.
*
* @template T
*
* @param iterable<T> $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()
Expand Down
10 changes: 10 additions & 0 deletions test/iterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down