How to cast array elements to strings in PHP?

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

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?

回答1:

A one-liner:

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

See PHP DOCS:

array_map

strval

Enjoy! ;)



回答2:

Are you looking for implode?

$array = array('lastname', 'email', 'phone');  $comma_separated = implode(",", $array);  echo $comma_separated; // lastname,email,phone 


回答3:

Not tested, but something like this should do it?

foreach($a as $key => $value) {     $new_arr[$key]=$value->__toString(); } $a=$new_arr; 


回答4:

I can't test it right now, but can you check what happens when you implode() such an array? The _toString should be invoked.



回答5:

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



回答6:

Is there any reason why you can't do the following?

$a = array(     (string) $objA,     (string) $objB, ); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!