Implode doesn’t work on classes


The PHP function implode is one I use frequently.
When you have an array of strings and want to put them in a string, separated by commas, you can either write a loop like this:

$arr = array('one', 'two', 'three', 'four', 'five');
$str = '';
foreach($arr as $item)
$str .= $item . ',';
$str = substr($item, 0, strlen($str) - 1);

or you can use the php function implode like this:

$arr = array('one', 'two', 'three', 'four', 'five');
$str = implode(',', $arr);

This is super!

__ToString Magic Method

On the other hand, there is the __ToString magic method for PHP classes. It allows you to give a string output for your class. Take this simple HTML paragraph class as example:

class p {
private $content = null;
public function __construct($content) {
$this->content = $content;
// Some more code
public function __ToString() {
return '<p>' . htmlentities($this->content) . '</p>';

The problem

Now when you want to combine both, it won’t work:

$arr = array();
$arr[0] = new p('test 1');
$arr[0] = new p('test 2');
$str = implode("\n", $arr);

This will give you a “Warning: implode() [function.implode]: Invalid arguments passed.”

No Responses to “Implode doesn’t work on classes”.

Leave a response