phparraysinterleave

Push static element between every original element of an array


I have a an array like so:

$fruit = array('Apple', 'Orange', 'Banana');

I would like to combine the array with a separator similar to implode but without converting the result to a string.

So instead of

implode('.', $fruit); // 'Apple.Orange.Banana'

the result should be:

array('Apple', '.', 'Orange', '.', 'Banana');

This could probably be achieved with loops, however, I am looking for the best possible solution. Maybe there is a native function that can accomplish that which I do not know of? Thanks in advance!


Solution

  • Use array_splice() with a reversed for loop

    Remember to remove 1 from count($fruit) so we won't add another . at the end of the array

    <?php
    
    $fruit = [ 'Apple', 'Orange', 'Banana' ];
    for ($i = count($fruit) - 1; $i > 0; $i--) {
        array_splice($fruit, $i, 0, '.');
    }
    
    var_dump($fruit);
    
    array(6) {
      [0]=>
      string(5) "Apple"
      [1]=>
      string(1) "."
      [2]=>
      string(6) "Orange"
      [3]=>
      string(1) "."
      [4]=>
      string(6) "Banana"
    }