Question

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?

Was it helpful?

Solution 2

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!

OTHER TIPS

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

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top