How to cast array elements to strings in PHP?
89,335
Solution 1
A one-liner:
$a = array_map('strval', $a);
// strval is a callback function
See PHP DOCS:
Solution 2
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 3
Not tested, but something like this should do it?
foreach($a as $key => $value) {
$new_arr[$key]=$value->__toString();
}
$a=$new_arr;
Solution 4
Are you looking for implode?
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
Comments
-
acme about 3 years
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? -
Kemo over 14 yearsread the question, it says "is there a one-liner or do I have to manually loop..." :)
-
Gordon over 14 yearsIt does. Simple
implode($array)
will do. -
Ben Everard over 14 yearsYes, and as I suggested in the comment to Alix's post I would have offered his solution had I have known about it.
-
Alix Axel over 14 years@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. -
acme over 14 yearsRight, I want the array to be still intact and only the elements in it casted to string.
-
Gordon over 14 years@Alix Oh, I see. Yes. Then implode won't do.
-
nikc.org over 14 years
explode(',', implode(',' $array))
then, perhaps? Although, the proposedarray_map
would be more elegant, this approach could be done like this, couldn't it? -
Alix Axel over 14 years@nikc: Not if the generated
__toString()
contains,
. -
acme over 14 yearsYes, 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 about 12 yearsNo, because my array consists of objects, not strings. And the result should be an array and not an imploded string.
-
Tasik about 2 yearsCan also be called like
return array_map(fn ($item) => strval($item), $items);
if you'd rather not reference the function 'strval' as a string.