'Implode array with array of glue strings

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?



Solution 1:[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!

Solution 2:[2]

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

Solution 3:[3]

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 :-)

Solution 4:[4]

$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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2
Solution 3 Community
Solution 4