acme
acme

Reputation: 14856

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?

Upvotes: 96

Views: 116777

Answers (7)

Nitin-web-dev
Nitin-web-dev

Reputation: 1

$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);

Upvotes: -2

Alix Axel
Alix Axel

Reputation: 154533

A one-liner:

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

See PHP DOCS:

array_map

strval

Upvotes: 235

Jan Jaso
Jan Jaso

Reputation: 41

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

Upvotes: 4

Martin Bean
Martin Bean

Reputation: 39389

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

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

Upvotes: -6

Ben Everard
Ben Everard

Reputation: 13804

Not tested, but something like this should do it?

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

Upvotes: 3

Pekka
Pekka

Reputation: 449395

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

Upvotes: -2

YOU
YOU

Reputation: 123821

Are you looking for implode?

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

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

echo $comma_separated; // lastname,email,phone

Upvotes: 2

Related Questions