1

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 there is a simple function that already does this.

2
  • Ok, the answers below are correct, but actually I stated the wrong outcome I am looking for. I actually want to yield "alpha,beta,delta". Is that possible? Commented Nov 23, 2010 at 21:44
  • You can use array_keys to get an array of the keys, and then implode that. Commented Nov 23, 2010 at 22:05

4 Answers 4

5

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);
}
?>
Sign up to request clarification or add additional context in comments.

Comments

3

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

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

Comments

1

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

Comments

1

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.

6 Comments

PHP has way too much aliases.. implode() vs explode() makes sense to me, but join() vs explode() ?? (since there ain't an unjoin() function or something like that..).. I know.. slightly offtopic.
@Enrico: agreed, but I'm not the one who threw all these aliases in PHP :P I just got used to join() because it's shorter, I guess, although the difference is obviously negligible.
The opposite of join is split, like in the Python camp. As nice as it is to accommodate for varying backgrounds, I agree that consistency is probably better - and don't detach this statement from the current context.
@FreelOne No worries.. I didn't mean to say that you created those aliases :p @erisco, thanks.. amazing how much I learn by answering other people's questions :p
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?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.