On Sun, Sep 19, 2021, at 8:11 AM, tyson andre 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
In cases where I do want it reindexed, the existing array_values() is fine in
most cases. Creating small, purpose-built tools that are easily composed is
generally the right strategy. The only time I could see a flag being a better
alternative is when the memory difference would be huge. Do we have a sense
for how much of a memory difference we'd be looking at by combining it into a
single operation?
(There's also the grossness of nesting functions inside each other, but the
answer to that is pipes, not more flags.)
--Larry Garfield
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php