How to cast array elements to strings in PHP?

PhpStringArraysCasting

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

A one-liner:

$a = array_map('strval', $a);
// strval is a callback function

See PHP DOCS:

array_map

strval

Solution 2 - Php

Not tested, but something like this should do it?

foreach($a as $key => $value) {
    $new_arr[$key]=$value->__toString();
}
$a=$new_arr;

Solution 3 - Php

Alix Axel has the nicest answer. You can also apply anything to the array though with array_map like...

//All your objects to string.
$a = array_map(function($o){return (string)$o;}, $a);
//All your objects to string with exclamation marks!!!
$a = array_map(function($o){return (string)$o."!!!";}, $a);

Enjoy

Solution 4 - Php

Are you looking for implode?

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

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

echo $comma_separated; // lastname,email,phone

Solution 5 - Php

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

Solution 6 - Php

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionacmeView Question on Stackoverflow
Solution 1 - PhpAlix AxelView Answer on Stackoverflow
Solution 2 - PhpBen EverardView Answer on Stackoverflow
Solution 3 - PhpJan JasoView Answer on Stackoverflow
Solution 4 - PhpYOUView Answer on Stackoverflow
Solution 5 - PhpPekkaView Answer on Stackoverflow
Solution 6 - PhpMartin BeanView Answer on Stackoverflow