| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace Improved; |
||
| 6 | |||
| 7 | /** |
||
| 8 | * Get the first 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_first(iterable $iterable, bool $required = false) |
||
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 15 | { |
||
| 16 | 9 | foreach ($iterable as $value) { |
|
| 17 | 7 | return $value; |
|
| 18 | } |
||
| 19 | |||
| 20 | 2 | if ($required) { |
|
| 21 | 1 | throw new \RangeException("Unable to get first element; iterable is empty"); |
|
| 22 | } |
||
| 23 | |||
| 24 | 1 | return null; |
|
| 25 | } |
||
| 26 |