Re: RFC proposal: function array_filter_list() to avoid subtle bugs/workarounds
| From: | Tim Düsterhus | Date: | Wed, 08 Feb 2023 16:50:32 +0000 |
| Subject: | Re: RFC proposal: function array_filter_list() to avoid subtle bugs/workarounds | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-119493@lists.php.net to get a copy of this message | ||
Hi
On 2/1/23 18:21, Sergii Shymko wrote:
For example: $originalList = ['first', '', 'last']; $filteredList = array_filter($originalList); var_export(filteredList); // array(0 => 'first', 2 => 'last') var_export(array_is_list($originalList)); // true var_export(array_is_list($filteredList)); // false The behavior is counterintuitive and can lead to subtle bugs, such as encoding issues: echo json_encode($originalList); // ["first", "", "last"] echo json_encode($filteredList); // {"0": "first", "2": "last"} The workaround is to post-process the filtered array with array_values() to reset the indexes. The proposal is to introduce a function array_filter_list() that would work solely on lists. It will have the same signature as array_filter() and will always return a valid list.I agree with the general premise that "array_filter turns lists into non-lists" is not great and I've encountered the issue myself more than I would like. However I also agree with the other replies that array_filter_list() is likely not the correct solution. I believe that defaults matter and as a developer when I have the choice between 'array_filter' and 'array_filter_list', the former is likely going to be the default, because it's shorter. So instead of remembering to wrap the array_filter() into array_values(), I have to remember which of the two functions I need. I also believe that non-array iterables should not be a second class citizen to arrays and would like to point to my email in this mailing list thread for the "[List/Assoc\unique]" RFC and thus a pretty similar topic, because it also applies here: https://externals.io/message/119070#119072 Perhaps the hypothetical "iterable\filter" function could be smart with regard to the handling of keys? If the input appears to be consecutively indexed, it is treated as a list and reindexed. Or it could default to dropping the keys, which I consider the better default, because dropping keys is *immediately* obvious when testing, whereas having holes in a list is not. Best regards Tim Düsterhus