Hi internals,
I'd like to propose adding array_zip() for PHP 8.7, and I'm looking for feedback before I write the RFC.
function array_zip(array ...$arrays): array {}
array_zip([1, 2], ['a', 'b']); // [[1, 'a'], [2, 'b']]
Today the usual way to zip is array_map(null, ...$arrays). As Nikita pointed out in 2019 (https://externals.io/message/105736), its single-array special case makes it unusable unless you know there are at least two arrays: array_map(null, [1, 2]) returns [1, 2], not [[1], [2]]. It also pads shorter arrays with null, and it cannot be called with zero arrays. Dik Takken suggested a separate zip function in that thread, but it was never followed up.
Proposed behaviour:
- Tuples are built by position. Keys are ignored and the result is a list of lists.
- One array still gives tuples: array_zip([1, 2]) === [[1], [2]].
- No arguments, or any empty input, gives [].
- The result is as long as the shortest input, as zip does in Haskell and Python.
- Non-array arguments throw a TypeError, as
array_merge()does.
I have a working implementation against master (about 80 lines in ext/standard/array.c, with tests): [PR link, or delete this sentence]
Two questions I'd especially like opinions on:
- With uneven lengths, should it truncate (as proposed) or throw a ValueError? The signature is variadic, so a mode flag can't be added later.
- Is array_zip() the right name? I'm not proposing a bare zip(), because far more userland code already declares a function named zip.
I'm not proposing to deprecate array_map(null, ...) here. If wanted, that can be voted on separately.
If there's interest, could someone grant me RFC karma on the wiki?
My wiki username is: jmediatechnology.
Thanks,
Julian Sawicki
Hi Julian,
After doing extensive research on the userland implementations, edge cases, and appetite for array transposition in PHP (based on Stack Overflow content only), I remain convinced that this is a feature that should be brought into the language.
Such a function would not only make the coding intention clear, succinct, and hopefully more performant; it would avoid the current pitfalls suffered by transpositions using array_map().
A variadic example of your initial email's example:
$twoD = [['a', 'b']];
var_export(
array_map(null, ...$twoD)
);
/* one-dimensional output:
array (
0 => 'a',
1 => 'b',
)
but the intention was probably:
array (
0 => array (0 => 'a'),
1 => array (0 => 'b'),
)
*/
Please see my thoughts from 2022: [Discussion before submission of array_transpose() RFC][https://news-web.php.net/php.internals/117582]
There are some important considerations that should be discussed in this potential RFC.
-
Perhaps the most likely data source to be transposed will be a database query result since it is a 2d array.
Not only might these payloads be arrays of associative arrays, they might be arrays of objects.
Should this feature be designed to accept shapes other than lists of lists and perhaps return a structure that respects that input structure? If not, then this feature will lose potentially relevant data (keys/properties) in the conversion and limit its utility. Furthermore, should this be designed to transpose an associative array of associative arrays? Why not? A foreach() inside of a foreach() already allows this. -
I am strongly opposed to the term "zip" in the function name. I understand that the term is borrowed from other languages, but:
- the process is technically transposition,
- zip has a preexisting connection with file compression, and
- some users may naively assume that zipping an array might have an interleaving effect.
I favourarray_transpose()like$transposed = array_transpose(...$queryResultSet);.
-
I agree that the function should throw exceptions when the input structure is not compliant with transposition. Foundationally, the function's intention is to re-orientate the data structure based on initial relationships, not change the data. Instead of converting a 1-d array into a 2-d array, I probably favor throwing an exception when input solely consists of a 1-d array on the grounds of foggy coding intention.
I mean, if you need that functionality, just callarray_chunk()with 1;
this way other developers won't be confused by your intention. Most typically, I expect to be spreading an empty or 2-d array inside this function, but I don't foresee a problem with arrays that have more than 2 levels because only the keys of the first two levels will be affected. -
Please remember to remove the placeholders that AI created in your emails before you send them. ("[PR link, or delete this sentence]")
-
Throwing an exception on non-matrix payloads will make the function simpler under the hood, but allowing uneven/gapped payloads means more utility and simpler replacement of existing
array_map(null, ...)implementations.
I don't have a strong opinion either way on this point.
I wish you good luck with the RFC because I want this to happen! If you need userland examples: I've shoveled many into a pile for you already: https://meta.stackoverflow.com/q/417663/2943403
mickmackusa