Search code examples
phpstringarrayscasting

How to cast array elements to strings in PHP?


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?


Solution

  • A one-liner:

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

    See PHP DOCS:

    array_map

    strval