Is there a php function like python's zip? Is there a php function like python's zip? python python

Is there a php function like python's zip?


As long as all the arrays are the same length, you can use array_map with null as the first argument.

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

If some of the arrays are shorter, they will be padded with nulls to the length of the longest, unlike python where the returned result is the length of the shortest array.


array_combine comes close.

Otherwise nothing like coding it yourself:

function array_zip($a1, $a2) {  for($i = 0; $i < min(length($a1), length($a2)); $i++) {    $out[$i] = [$a1[$i], $a2[$i]];  }  return $out;}


Try this function to create an array of arrays similar to Python’s zip:

function zip() {    $args = func_get_args();    $zipped = array();    $n = count($args);    for ($i=0; $i<$n; ++$i) {        reset($args[$i]);    }    while ($n) {        $tmp = array();        for ($i=0; $i<$n; ++$i) {            if (key($args[$i]) === null) {                break 2;            }            $tmp[] = current($args[$i]);            next($args[$i]);        }        $zipped[] = $tmp;    }    return $zipped;}

You can pass this function as many array as you want with as many items as you want.