Skip to content

Instantly share code, notes, and snippets.

@mcuyar
Last active May 10, 2022 13:04
Show Gist options
  • Save mcuyar/8f14f6f626a708868d3e3ef1a7996c25 to your computer and use it in GitHub Desktop.
Save mcuyar/8f14f6f626a708868d3e3ef1a7996c25 to your computer and use it in GitHub Desktop.
create a list which alternates between elements of the two input lists, starting with the first element of the first list, then the first element of the second list and so on, until one of the lists doesn't have the next element, then you stop.
<?php
function zipLists(array $first, array $second, $index = 0, $carry = []): array
{
$firstValue = $first[$index] ?? null;
if(is_null($firstValue)) {
return $carry;
}
$carry[] = $firstValue;
$secondValue = $second[$index] ?? null;
if(is_null($secondValue)) {
return $carry;
}
$carry[] = $secondValue;
$index = $index + 1;
return zipLists($first, $second, $index, $carry);
}
zipLists([], []); // []
zipLists([], [1,2,3]); // []
zipLists([1,2,3], []); // [1]
zipLists([1,2], [3]); // [1,3,2]
zipLists([1,2,3,4,5], [11, 12, 13]); // [1,11,2,12,3,13,4]
zipLists([9,9,9], [8,8,8]); //[9,8,9,8,9,8]
zipLists([1,2,3], [4,5,6,7]); //[1,4,2,5,3,6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment