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?
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);
The implode() function returns a string from the elements of an array. Note: The implode() function accept its parameters in either order.
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.
A one-liner:
$a = array_map('strval', $a); // strval is a callback function
See PHP DOCS:
array_map
strval
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With