Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP – Implode as 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading