PHP RFC: array_reindex function
- Version: 0.1
- Date: 2019-03-07
- Author: Andrey Gromov, andrewgrom@rambler.ru
- Status: Draft
- First Published at: http://wiki.php.net/rfc/array_reindex
Introduction
It is not rare case when we need only values from some array. Usually we use constructs like:
$array = array_values($array);
In fact I see many code like
$new_array = array_values($array);
without any usage of $array after this line.
Also, common case is skip null or empty values from this resulting array, then we use
if(empty($value)) continue;
inside loop.
In those cases array_values create redundant structures, and ifs slow down execution and raise complexity of code.
Proposal
I propose to add new “array_reindex” function into standard library. This function will receive array by reference, optionally remove useless values and make in-place conversion to packed array.
array_reindex ( array &$array [, int $flags = ARRAY_REINDEX_NO_SKIP ] ) : bool
Where $flags is bitmask of filtering constants.
If array is kept unchanged then returns FALSE, otherwise returns TRUE.
Backward Incompatible Changes
Only if the same function declared inside user code.
Proposed PHP Version(s)
Next PHP 7.x or PHP 8.
New Constants
ARRAY_REINDEX_NO_SKIP = 1<<0; // Keep all values ARRAY_REINDEX_SKIP_NULL = 1<<1; // Skip NULL values const ARRAY_REINDEX_SKIP_EMPTY = 1<<2; //Skip empty(false) values
In current realisation it is possible to use all constant simultaneously and only most greedly will be used.
Future Scope
Maybe extend filtering scope.
Patches and Tests
I will write tests after(if) I receive green light. :)
Implementation
Review is needed. I not sure if my code does not have any problems. https://github.com/php/php-src/compare/master...rjhdby:array_reindex