0

If have this array:

$a = array("one", "two", "three");

I want to transform this into this string:

$s = "one, two, three";

Is there a paste function in PHP?

E.g.:

$s = paste($a, sep=", ");
0

2 Answers 2

3

Use implode:

$s = implode(', ',$a);
Sign up to request clarification or add additional context in comments.

3 Comments

shoulb be $s = implode(', ',$a); no? (', ' instead of ',')
ya sure. ',' is separator we can use any string or special character.
This again shows that you need to know the answer to be able to search for it :-( In other programming languages (e.g. R) this operation is called paste, so why doesn't the documentation for implode contain that common term? Would make finding this so much easier. Thank you for helping me, @Manibharathi!
0
$a = array("one", "two", "three");

foreach($a as $value) {
   $string = $string . ($value != '' ? '' : ', ') . $value;
}

4 Comments

Haha, ternary operator. I'm confused! ;)
You know I was trying to come up with the least obvious answer right? I mean 681 rep and your asking about array imploding? :)
My rep is for asking noob questions that other noobs find helpful, not for knowing stuff :-)
Ah ok, sorry for my strange answer then. It's correct though! ;)

Your Answer

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