Skip to content

Commit d4e5fcd

Browse files
Ayeshnicolas-grekas
andcommitted
[PHP 8.5] Add array_first and array_last
Adds polyfills for the PHP 8.5's `array_first` and `array_last` functions. The polyfills would have been a bit cleaner if we used the `array_key_first` and `array_key_last` functions, but they were added in PHP 7.3, and are not available on PHP 7.2. This adds the same tests from php-src patch. - [RFC: `array_first()` and `array_last()`](https://wiki.php.net/rfc/array_first_last) - [php-src commit](php/php-src@168343d) - [PHP.Watch polyfill for PHP 8.0+](https://php.watch/versions/8.5/array_first-array_last) Co-authored-by: Nicolas Grekas <nicolas.grekas@gmail.com>
1 parent 6fedf31 commit d4e5fcd

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

Php85.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,18 @@ public static function get_exception_handler(): ?callable
3333

3434
return $handler;
3535
}
36+
37+
public static function array_first(array $array)
38+
{
39+
foreach ($array as $value) {
40+
return $value;
41+
}
42+
43+
return null;
44+
}
45+
46+
public static function array_last(array $array)
47+
{
48+
return $array ? current(array_slice($array, -1)) : null;
49+
}
3650
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ This component provides features added to PHP 8.5 core:
55

66
- [`get_error_handler` and `get_exception_handler`](https://wiki.php.net/rfc/get-error-exception-handler)
77
- [`NoDiscard`](https://wiki.php.net/rfc/marking_return_value_as_important)
8+
- [`array_first` and `array_last`](https://wiki.php.net/rfc/array_first_last)
89

910
More information can be found in the
1011
[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md).

bootstrap.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,11 @@ function get_error_handler(): ?callable { return p\Php85::get_error_handler(); }
2222
if (!function_exists('get_exception_handler')) {
2323
function get_exception_handler(): ?callable { return p\Php85::get_exception_handler(); }
2424
}
25+
26+
if (!function_exists('array_first')) {
27+
function array_first(array $array) { return p\Php85::array_first($array); }
28+
}
29+
30+
if (!function_exists('array_last')) {
31+
function array_last(array $array) { return p\Php85::array_last($array); }
32+
}

0 commit comments

Comments
 (0)