Skip to content

Commit 8dc4cfa

Browse files
committed
Added \iter\last().
1 parent 4e1e8b5 commit 8dc4cfa

2 files changed

Lines changed: 18 additions & 0 deletions

File tree

src/iter.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1290,6 +1290,19 @@ function tap(callable $function, iterable $iterable): \Iterator {
12901290
}
12911291
}
12921292

1293+
/**
1294+
* Returns the last value of the specified iterable.
1295+
*
1296+
* @param iterable $iterable Iterable.
1297+
*
1298+
* @return mixed Last value of the iterable if it contains values, otherwise null.
1299+
*/
1300+
function last(iterable $iterable): mixed {
1301+
foreach ($iterable as $value) {}
1302+
1303+
return $value ?? null;
1304+
}
1305+
12931306
/*
12941307
* Python:
12951308
* compress()

test/iterTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -644,6 +644,11 @@ public function testTap() {
644644
toArray(tap([$mock, 'foo'], [1, 2, 3]))
645645
);
646646
}
647+
648+
public function testLast() {
649+
self::assertSame(3, last(range(1, 3)));
650+
self::assertNull(last(new \EmptyIterator()));
651+
}
647652
}
648653

649654
class _CountableTestDummy implements \Countable {

0 commit comments

Comments
 (0)