Re: Proposal: Adding an ARRAY_FILTER_REINDEX flag to array_values
| From: | Eugene Sidelnyk | Date: | Mon, 20 Sep 2021 10:02:12 +0000 |
| Subject: | Re: Proposal: Adding an ARRAY_FILTER_REINDEX flag to array_values | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-116105@lists.php.net to get a copy of this message | ||
Hi, I myself faced such bugs because filter function preserves keys. From
my experience it is not that easy to locate bug like this. In my case I
rewrote solution in other way than it was originally written. Only later I
realized that root cause was array_filter
On Sun, Sep 19, 2021, 4:11 PM tyson andre <tysonandre775@hotmail.com> wrote:
> 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
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>