views:

177

answers:

5

If I have a array with objects:

$a = array($objA, $objB);

(each object has a __toString()-method)

How can I cast all array elements to string so that array $a contains no more objects but their string representation? Is there a one-liner or do I have to manually loop through the array?

+2  A: 

Are you looking for implode?

$array = array('lastname', 'email', 'phone');

$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone
S.Mark
A: 

I can't test it right now, but can you check what happens when you implode() such an array? The _toString should be invoked.

Pekka
It does. Simple `implode($array)` will do.
Gordon
@Gordon: It'll merge all the strings in one though, I think the OP wants to keep the `__toString()` generated strings in the corresponding array elements.
Alix Axel
Right, I want the array to be still intact and only the elements in it casted to string.
acme
@Alix Oh, I see. Yes. Then implode won't do.
Gordon
`explode(',', implode(',' $array))` then, perhaps? Although, the proposed `array_map` would be more elegant, this approach *could* be done like this, couldn't it?
nikc
@nikc: Not if the generated `__toString()` contains `,`.
Alix Axel
Ah yes, of course.
nikc
+8  A: 

A one-liner:

$a = array_map('strval', $a);

Enjoy! ;)

Alix Axel
Damn, wish I knew this before posting my answer. +1
ILMV
implode( ',' , array_map('strval', $a ) );would do the job prolly
Kemo
@Kemo: I don't think he wants to do that.
Alix Axel
@Alix Axel right, the question got me a little confused
Kemo
Perfect, this was what I wanted! Thanks!
acme
@acme: You're welcome. =)
Alix Axel
A: 

Not tested, but something like this should do it?

foreach($a as $key => $value) {
    $new_arr[$key]=$value->__toString();
}
$a=$new_arr;
ILMV
read the question, it says "is there a one-liner or do I have to manually loop..." :)
Kemo
Yes, and as I suggested in the comment to Alix's post I would have offered his solution had I have known about it.
ILMV
Why has this received a negative vote?
ILMV
A: 

Is there any reason why you can't do the following?

$a = array(
    $objA->__toString(),
    $objB->__toString(),
);
Martin Bean
Yes, because actually I don't know how many elements there are in the array. The example above was just reduced to two elements to make it more clear.
acme