I have two arrays. For example:
$arr1 = [1, 2, 3, 7, 8, 9]; $arr2 = [4, 5, 6, 10, 11, 12, 13, 14];
How can I combine them to general array by taking per 3 elements from every array? The output should be:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
The main idea is taking per 3 elements. Later when I understand the algorithm, the arrays will have objects, not digits. I need to understand how I can to combine two arrays by taking per 3 elements from every array.
Advertisement
Answer
This came to mind…
Just keep looping while either array has any elements.
Suck the first three elements from each array and push them into your result array until there is nothing left in the two arrays.
Seems simple enough to me. 🙂
Code: (Demo)
$arr1 = [1, 2, 3, 7, 8, 9]; $arr2 = [4, 5, 6, 10, 11, 12, 13, 14]; $result = []; while ($arr1 || $arr2) { array_push($result, ...array_splice($arr1, 0, 3), ...array_splice($arr2, 0, 3)); } var_export($result);
Output:
array ( 0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5, 5 => 6, 6 => 7, 7 => 8, 8 => 9, 9 => 10, 10 => 11, 11 => 12, 12 => 13, 13 => 14, )
If you don’t want to mutate your original input arrays, this will do: (Demo)
$result = []; for ($i = 0; isset($arr1[$i]) || isset($arr2[$i]); $i += 3) { array_push($result, ...array_slice($arr1, $i, 3), ...array_slice($arr2, $i, 3)); } var_export($result);