Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 818
acme Avatar asked Jan 25 '10 10:01

acme


People also ask

How we can convert a multidimensional array to string without any loop in PHP?

function convert_multi_array($array) { foreach($array as $value) { if(count($value) > 1) { $array = implode("~", $value); } $array = implode("&", $value); } print_r($array); } $arr = array(array("blue", "red", "green"), array("one", "three", "twenty")); convert_multi_array($arr);

What is the name of function used to convert an array into a string?

The implode() function returns a string from the elements of an array. Note: The implode() function accept its parameters in either order.

How do you implode an array?

The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function. If we have an array of elements, we can use the implode() function to join them all to form one string.


1 Answers

A one-liner:

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

See PHP DOCS:

array_map

strval

like image 141
Alix Axel Avatar answered Sep 18 '22 15:09

Alix Axel