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:

array_map

strval

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
Share:
89,335
acme
Author by

acme

Diving into web development since over 15 years.

Updated on April 10, 2021

Comments

  • acme
    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
    Kemo over 14 years
    read the question, it says "is there a one-liner or do I have to manually loop..." :)
  • Gordon
    Gordon over 14 years
    It does. Simple implode($array) will do.
  • Ben Everard
    Ben Everard over 14 years
    Yes, 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
    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
    acme over 14 years
    Right, I want the array to be still intact and only the elements in it casted to string.
  • Gordon
    Gordon over 14 years
    @Alix Oh, I see. Yes. Then implode won't do.
  • nikc.org
    nikc.org over 14 years
    explode(',', implode(',' $array)) then, perhaps? Although, the proposed array_map would be more elegant, this approach could be done like this, couldn't it?
  • Alix Axel
    Alix Axel over 14 years
    @nikc: Not if the generated __toString() contains ,.
  • acme
    acme over 14 years
    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
    acme about 12 years
    No, because my array consists of objects, not strings. And the result should be an array and not an imploded string.
  • Tasik
    Tasik about 2 years
    Can also be called like return array_map(fn ($item) => strval($item), $items); if you'd rather not reference the function 'strval' as a string.