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?

2

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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!

1 Comment

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

1 Comment

This is Not An Answer -- it is a close vote or a comment at most.
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.

2 Comments

trim would be useful here for the space also.
$b[$k] Is not guaranteed to exist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.