0

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?

8
  • In your example $newArray is a string not an array. Commented Dec 5, 2020 at 18:28
  • Sorry, I forgot to add the line $newArray = explode(".", $newArray);, I edited the post.
    – Acsrel
    Commented Dec 5, 2020 at 18:29
  • Just a foreach() loop is about the simplest.
    – Nigel Ren
    Commented Dec 5, 2020 at 18:30
  • Define "cleaner". It's a straightforward solution, easy to understand and does the job. What are you looking to improve?
    – El_Vanja
    Commented Dec 5, 2020 at 18:30
  • 1
    That's true, although, I'm using the foreach() way, as it's also better just in case one of the elements had a dot in them.
    – Acsrel
    Commented Dec 5, 2020 at 18:53

1 Answer 1

1
$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);

Not the answer you're looking for? Browse other questions tagged or ask your own question.