How to cast array elements to strings in PHP?

Solution 1:

A one-liner:

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

See PHP DOCS:

array_map

strval

Solution 2:

Not tested, but something like this should do it?

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

Solution 3:

Are you looking for implode?

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

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

echo $comma_separated; // lastname,email,phone

Solution 4:

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