Home >Backend Development >PHP Tutorial >How to Replicate Python\'s zip() Function in PHP?

How to Replicate Python\'s zip() Function in PHP?

DDD
DDDOriginal
2024-11-28 05:17:17908browse

How to Replicate Python's zip() Function in PHP?

PHP Equivalent of Python's zip() Function

Python's zip() function provides a simple and concise way to combine multiple lists or sequences into an iterable of tuples. The tuples contain elements at the corresponding index from each input sequence. In PHP, there is no built-in zip() function. However, you can achieve similar functionality using array_map().

Solution Using Array Map:

As long as all input arrays have the same length, you can use array_map() with null as the first argument. The null argument ignores the callback function parameter and passes all input arrays as arguments to map():

array_map(null, $a, $b, $c, ...);

This will return an array of tuples, where each tuple contains elements at the corresponding index from each input array. For example, given the following input arrays:

$a = [1, 2, 3, 4];
$b = ['a', 'b', 'c', 'd'];
$c = ['x', 'y', 'z', 'w'];

Calling array_map() as shown below will produce the following result:

array_map(null, $a, $b, $c);
    [1, 'a', 'x']
    [2, 'b', 'y']
    [3, 'c', 'z']
    [4, 'd', 'w']

Note: If some input arrays have different lengths, they will be padded with null values to the length of the longest array. This differs from Python's zip(), which returns an iterable with the length of the shortest array.

The above is the detailed content of How to Replicate Python\'s zip() Function in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn