Skip to content

Instantly share code, notes, and snippets.

@rsuper
Last active October 24, 2018 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsuper/1cd91b6f756eacd27e958820a2acaf82 to your computer and use it in GitHub Desktop.
Save rsuper/1cd91b6f756eacd27e958820a2acaf82 to your computer and use it in GitHub Desktop.
PHP 'zip' arrays, like a zipper effect.
// Suppose you have 2 array and you want each value from array 2 to appear next to the value of array 1 with the same index...
$array1 = ['This', 'supposed', 'make', 'sentence'];
$array2 = ['is', 'to', 'a'];
$num1 = (count($array1) - 1) * 2;
$num2 = (count($array2) - 0) * 2;
$leftIndex = $num1 > 0 ? range(0, $num1, 2) : [0];
$rightIndexes = $num2 > 2 ? range(1, $num2, 2) : [1];
$arr1 = array_combine($leftIndex, $array1);
$arr2 = array_combine($rightIndexes, $array2);
$array = $arr1 + $arr2;
// Rorder the array
ksort($array);
// Once the array is correct, we can create a new, nicely indexed array in case array1 and 2 have different number of values
$array = array_values($array);
echo implode(' ', $array);
// Output: This is supposed to make a sentence
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment