Skip to content

Instantly share code, notes, and snippets.

@nabil-boag
Created January 21, 2014 09:46
Show Gist options
  • Save nabil-boag/8537228 to your computer and use it in GitHub Desktop.
Save nabil-boag/8537228 to your computer and use it in GitHub Desktop.
PHP Function for array zip merge. Merges two arrays like a zipping. Uneven sized arrays get items appended to the end.
/**
* Merges two arrays like a zipping. Uneven sized arrays get items
* appended to the end.
*
* @param array $a An array to merge
* @param array $b Another array to merge
* @return array An array of merged values
*/
function array_zip_merge(array $a, array $b) {
$return = array();
$count_a = count($a);
$count_b = count($b);
if ($count_b < $count_a) {
// Ensure $b is greater or equal to $a
$temp = $a;
$b = $a;
$a = $temp;
}
// Zip arrays
for ($i = 0; $i < $count_a; $i++) {
$return = array_merge_recursive($return, array_slice($a, $i, 1, true));
$return = array_merge_recursive($return, array_slice($b, $i, 1, true));
}
$difference = $count_b - $count_a;
if ($difference) {
// There are more items to add on end so pop them at the end
$return = array_merge_recursive($return,
array_slice($b, $count_a, $difference, true));
}
return $return;
}
@Lachee
Copy link

Lachee commented Dec 11, 2020

The swap function is wrong, it just duplicates the a and doesn't update the counts.

        if ($count_a > $count_b) {
            // Ensure $b is greater or equal to $a
            $temp = $b;
            $b = $a;
            $a = $temp;

            $count_a = count($a);
            $count_b = count($b);
        }

This is a correct implementation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment