Acsrel
Acsrel

Reputation: 35

How do I add an element between all the other elements in an array

I have a question, let's say I have this array:

$array = ["one", "two", "three", "four"];

And I want to add "test" between elements in the array, so it becomes like this:

$array = ["test", "one", "test", "two", "test", "three", "test", "four"];

My current way of doing it is by doing this:

$array = ["one", "two", "three", "four"];
$newArray = "test." . implode("test.", $array);
$newArray = explode(".", $newArray);

But I want a way that's cleaner, can somebody help me please?

Upvotes: 0

Views: 47

Answers (1)

loydg
loydg

Reputation: 204

$array = [...]; // Defined in question
$newArray = [];
foreach ($array as $key => $value) {
    $even = $key * 2;
    $odd = $even + 1;
    $newArray[$odd] = $value;
    $newArray[$even] = "test";

    // Or just reusing $key
    // $key *= 2;
    // $newArray[$key + 1] = $value;
    // $newArray[$key] = "test";
}
var_dump($newArray);

Upvotes: 1

Related Questions