开发者

Break apart an array in PHP - Convert to String

开发者 https://www.devze.com 2023-01-26 20:12 出处:网络
I have an array: $arr[\'alpha\'] = \'a\'; $arr[\'beta\'] = \'b\'; $arr[\'delta\'] = \'d\'; Does anyone know if PHP has a function to take the above array and produce:

I have an array:

$arr['alpha'] = 'a';
$arr['beta'] = 'b';
$arr['delta'] = 'd';

Does anyone know if PHP has a function to take the above array and produce:

$some_string -- where $some_sting is set to the associative values of the array such that if I echoed $some_sting I would see:

"a,b,d"

Thanks.

I know how to write a for loop to produce the result, but I am curious if ther开发者_如何学Ce is a simple function that already does this.


You can use implode()

Update:

About your comment under FreekOne's answer you wrote:

Ok, the answers herein are correct, but actually I stated the wrong outcome I am looking for. I actually want to yield "alpha,beta,delta". Is that possible?

This is how you do that..

<?php
function implode_key($glue = "", $pieces = array()) {
    $arrK = array_keys($pieces);
    return implode($glue, $arrK);
}
?>


$some_string = implode(',',$arr); //a,b,d

$some_string = implode(',',array_keys($arr)); //alpha,beta,delta


Use PHP's implode function:

http://php.net/manual/en/function.implode.php

Prototype:

string implode ( string $glue , array $pieces )

So you could do this:

$glued = implode(',' , $arr);


For the sake of variety, join() can also be used, but it's nothing more than an alias of the already suggested implode().

So, doing an echo join(',',$arr); would output a,b,c as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号