Proposal: Adding an ARRAY_FILTER_REINDEX flag to array_values
| From: | tyson andre | Date: | Sun, 19 Sep 2021 13:11:47 +0000 |
| Subject: | Proposal: Adding an ARRAY_FILTER_REINDEX flag to array_values | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-116097@lists.php.net to get a copy of this message | ||
Hi internals,
Currently, array_filter will always return the original keys.
This often requires an additional wrapping call of array_values(array_filter(...)) to reindex the
keys and return a list.
(or applications may not realize there will be gaps in the keys until it causes a bug or unexpected
JSON encoding, etc.)
PHP is also more memory/time efficient at creating packed arrays than it is at creating associative
arrays.
What are your thoughts on adding
ARRAY_FILTER_REINDEX, to ignore the original
int/string keys and replace them with 0, 1, 2, ...
```
php > echo json_encode(array_filter([5,6,7,8], fn($value) => $value % 2 > 0));
{"0":5,"2":7}
// proposed flag
php > echo json_encode(array_filter([5,6,7,8], fn($value) => $value % 2 > 0,
ARRAY_FILTER_REINDEX));
[5,7]
```
https://www.php.net/array_filter already has the
int $mode = 0 which accepts the bit flags ARRAY_FILTER_USE_KEY and
ARRAY_FILTER_USE_BOTH
These could be then be combined with the proposed bit flag ARRAY_FILTER_REINDEX, e.g.
to filter an array based on both the array keys and values, and return a list without gaps.
(and if $callback is null, this would return a list containing only the truthy values)
Thoughts?
Thanks,
Tyson