Alternative
Leaning on the array_*
functions, you could consider the following:
function interleave(string $sep, array $arr): array {
return array_slice(array_merge(...array_map(fn($elem) => [$sep, $elem], $arr)), 1);
}
Due to the use of inbuilt functions and no explicit looping, it exceeds the speed of the looping array_splice
implementation around the 10 element mark, so the trade-off between terse implementation and performance may be worth it in your case.
Explanation
When called like so:
interleave('.', ['Apple', 'Orange', 'Banana']);
does the following (from the inside out):
Map
Map each element to a pair ['.', $elem]
:
$mapped = array_map(fn($elem) => ['.', $elem], ['Apple', 'Orange', 'Banana']);
resulting in:
Array
(
[0] => Array
(
[0] => .
[1] => Apple
)
[1] => Array
(
[0] => .
[1] => Orange
)
[2] => Array
(
[0] => .
[1] => Banana
)
)
Merge
Flatten the array using array_merge
taking advantage of the fact that, from the documentation:
If [...] the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
$merged = array_merge(...$mapped);
resulting in:
Array
(
[0] => .
[1] => Apple
[2] => .
[3] => Orange
[4] => .
[5] => Banana
)
Slice
Slice off the first extra separator:
$sliced = array_slice($merged, 1);
resulting in:
Array
(
[0] => Apple
[1] => .
[2] => Orange
[3] => .
[4] => Banana
)