Level 75
$array = ['a', 'b', 'c'];
$char = 'x';
$newArray = collect($array)->flatMap(function ($item) use ($char) {
return [$item, $char];
})->slice(0, -1)->toArray();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi everyone,
Given I have this array:
$array = ['a', 'b', 'c'];
I want to insert a new value between each item, for example:
$newArray = insertBetweenEachItem($array, 'x');
// ['a', 'x', 'b', 'x', 'c']
Thank you!
$array = ['a', 'b', 'c'];
$char = 'x';
$newArray = collect($array)->flatMap(function ($item) use ($char) {
return [$item, $char];
})->slice(0, -1)->toArray();
Please or to participate in this conversation.