1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Improved; |
||
6 | |||
7 | /** |
||
8 | * Get the last element of an iterable. |
||
9 | * |
||
10 | * @param iterable $iterable |
||
11 | * @param bool $required Throw RangeException instead of returning null for empty iterable |
||
12 | * @return mixed |
||
13 | */ |
||
14 | function iterable_last(iterable $iterable, bool $required = false) |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
15 | { |
||
16 | 8 | if (is_array($iterable) && $iterable !== []) { |
|
17 | 1 | return end($iterable); |
|
18 | } |
||
19 | |||
20 | 7 | $last = null; |
|
21 | 7 | $empty = true; // because $last can be any value including null. |
|
22 | |||
23 | 7 | foreach ($iterable as $value) { |
|
24 | 5 | $last = $value; |
|
25 | 5 | $empty = false; |
|
26 | } |
||
27 | |||
28 | 7 | if ($empty && $required) { |
|
29 | 1 | throw new \RangeException("Unable to get last element; iterable is empty"); |
|
30 | } |
||
31 | |||
32 | 6 | return $last; |
|
33 | } |
||
34 |