1

I have a awkward need but I need to interleave an array with another array before imploding the result. I guess my better option would be less talk more example

Array number one

[0] => "John has a ", [1] => "and a", [2] => "!" 

Array number two

[0] => 'Slingshot", [1] => "Potato"

I need to produce

John has a Slingshot and a Potato!

My question is can I do that with an implode or I must build my own function?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
php_nub_qq
  • 15,199
  • 21
  • 74
  • 144
  • [implode does not take 2 array's as argument only a separator and an array so it would not work.](http://php.net/manual/en/function.implode.php) – Prix Jun 11 '13 at 20:07
  • Dupe of: [Push elements from two arrays in an alternating fashion to form a new flat array](https://stackoverflow.com/q/11082461/2943403) + `implode()` – mickmackusa Sep 03 '22 at 06:30

4 Answers4

3

Simple Solution

$a = [0 => "John has a", 1 => "and a", 2 => "!" ];
$b = [0 => "Slingshot", 1 => "Potato"];
vsprintf(implode(" %s ", $a),$b);

Use array_map before implode

$a = [0 => "John has a", 1 => "and a", 2 => "!" ];
$b = [0 => "Slingshot", 1 => "Potato"];

$data = [];
foreach(array_map(null, $a, $b) as $part) {
    $data = array_merge($data, $part);
}
echo implode(" ", $data);

Another Example :

$data = array_reduce(array_map(null, $a, $b), function($a,$b){
    return  array_merge($a, $b);
},array());

echo implode(" ", $data);

Both Would output

 John has a Slingshot and a Potato !  

Demos

Live DEMO 1

Live DEMO 2

Baba
  • 94,024
  • 28
  • 166
  • 217
1

Might be worth looking at the top answer on Interleaving multiple arrays into a single array which seems to be a slightly more general (for n arrays, not 2) version of what otherwise exactly what you're after :-)

Community
  • 1
  • 1
James Green
  • 1,693
  • 11
  • 18
1

Adapted from comment above.

Are you sure you don't just want string formatting?

echo vsprintf("John has a %s and a %s!", array('slingshot', 'potato'));

Output:

John has a slingshot and a potato!
Community
  • 1
  • 1
benastan
  • 2,268
  • 15
  • 14
  • This answer does not respect the seemingly dynamic arrays provided in the question body. It is also an antipattern to write `echo vsprintf()` -- if you are going to print it with `echo` then you should more directly just call `vprintf()`. – mickmackusa Apr 22 '22 at 06:25
0
$a = [0 => "John has a ", 1 => "and a", 2 => "!" ];
$b = [0 => "Slingshot", 1 => "Potato"];

foreach($a AS $k=>$v){
    echo trim($v).' '.trim($b[$k]).' ';
}

If you fix your spaces so they're consistent :)

You'd also want to add an isset() check too probably.

Jessica
  • 7,075
  • 28
  • 39