如何在 PHP 中将数组元素转换为字符串?

如果我有一个包含对象的数组:

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

(每个对象都有一个 __toString()方法)

如何将所有数组元素强制转换为字符串,使数组 $a不再包含对象,而只包含它们的字符串表示?是否有一行程序或者我必须手动通过数组循环?

98699 次浏览

Are you looking for implode?

$array = array('lastname', 'email', 'phone');


$comma_separated = implode(",", $array);


echo $comma_separated; // lastname,email,phone

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

A one-liner:

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

See PHP DOCS:

array_map

strval

Not tested, but something like this should do it?

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

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

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

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

$str1 = "pankaj";
$str2 = array("sam",'pankaj',"hello");
function Search($x ,$y){
$search = $x;
$arr = $y;
foreach($y as $key => $value){
$str = array_search($x, $y);
if($str == $key){
echo $key ."=>".$value;
echo "<br>".gettype($value);
}
}
}
Search($str1 ,$str2);