Skip to content

[PHP 8.5] Add array_first and array_last #525

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 1.x
Choose a base branch
from

Conversation

Ayesh
Copy link
Contributor

@Ayesh Ayesh commented May 7, 2025

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.

@Ayesh Ayesh force-pushed the array_first_last branch from 20efa08 to d67a9bc Compare May 9, 2025 07:47
@mtarld
Copy link

mtarld commented May 9, 2025

I'm afraid that the current array_last implementation doesn't work with associative arrays.
Indeed:

var_dump(array_slice(['a' => 2, 'b' => 1], -1, 1)[0]);

outputs a warning telling Undefined array key 0, whereas it should dump 1.

@nicolas-grekas
Copy link
Member

I guess array_key_last should be used then

@Ayesh
Copy link
Contributor Author

Ayesh commented May 9, 2025

@nicolas-grekas is it OK to bump the minimum PHP version to 7.3? If we have array_key_first/last, it would make this much more cleaner.

@nicolas-grekas
Copy link
Member

Ah right, then current(array_slice()) should do it

@Ayesh Ayesh force-pushed the array_first_last branch from 2f5c5fb to 3c10365 Compare May 9, 2025 10:16
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 <[email protected]>
@Ayesh Ayesh force-pushed the array_first_last branch from 3c10365 to 933d80b Compare May 9, 2025 10:19
@Ayesh
Copy link
Contributor Author

Ayesh commented May 9, 2025

Updated with current(array_slice), and the other change suggestions from Nicolas. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants