tags:

views:

180

answers:

4

Python has a nice zip function ( http://docs.python.org/library/functions.html#zip ) is there a php equivalent?

+3  A: 

array_combine comes close.

Otherwise nothing like coding it yourself:

function array_zip($a1, $a2) {
  for($i = 0, $i < max(length($a1), length($a2)); $i++) {
    $out[$i] = [$a1[$i], $a2[$i]];
  }
  return $out;
}
Jakub Hampl
+2  A: 

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.

Gumbo
+1  A: 

array_map with null as the first argument.

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

Aaron Gallagher
Did you actually try that? `array_map` does not behave like Python’s `zip`. `array_map(null, array(1,2), array(3))` returns `array(array(1,3), array(2,null))` while `zip([1,2], [3])` just returns `[(1,2)]`.
Gumbo
A: 

I wrote a zip() functions for my PHP implementation of enum.
The code has been modified to allow for a Python-style zip() as well as Ruby-style. The difference is explained in the comments:

/*
 * This is a Python/Ruby style zip()
 *
 * zip(array $a1, array $a2, ... array $an, [bool $python=true])
 *
 * The last argument is an optional bool that determines the how the function
 * handles when the array arguments are different in length
 *
 * By default, it does it the Python way, that is, the returned array will
 * be truncated to the length of the shortest argument
 *
 * If set to FALSE, it does it the Ruby way, and NULL values are used to
 * fill the undefined entries
 *
 */
function zip() {
    $args = func_get_args();

    $ruby = array_pop($args);
    if (is_array($ruby))
        $args[] = $ruby;

    $counts = array_map('count', $args);
    $count = ($ruby) ? min($counts) : max($counts);
    $zipped = array();

    for ($i = 0; $i < $count; $i++) {
        for ($j = 0; $j < count($args); $j++) {
            $val = (isset($args[$j][$i])) ? $args[$j][$i] : null;
            $zipped[$i][$j] = $val;
        }
    }
    return $zipped;
}

Example:

$pythonzip = zip(array(1,2,3), array(4,5),  array(6,7,8));
$rubyzip   = zip(array(1,2,3), array(4,5),  array(6,7,8), false);

echo '<pre>';
print_r($pythonzip);
print_r($rubyzip);
echo '<pre>';
quantumSoup